# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Quality-diversity successive halving and fidelity-aware Bayesian proposals.
"""Promote designs within descriptor niches using a hard resource budget."""
from dataclasses import dataclass
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from qdpy.containers import CVTGrid, Grid
from qdpy.phenotype import Features, Fitness, Individual
from .bayesian import _expected_improvement, _region_probabilities
from .modern import _bounds, _positive_int
__all__ = ["QDHyperband", "BOPElitesHyperband", "FidelityTrial"]
## @brief One scheduled design measurement and the resource units it consumed.
[docs]
@dataclass(frozen=True)
class FidelityTrial:
"""A failed evaluation has fitness and descriptors set to None."""
genome: tuple[float, ...]
fidelity: int
fitness: float | None
descriptors: tuple[float, ...] | None
def _bracket(levels, eta, depth):
"""Return the initial size and all successive-halving rungs."""
size = -(-(len(levels) * eta ** depth) // (depth + 1))
return tuple((level, size // eta ** rung) for rung, level in enumerate(levels[-depth - 1:]))
def _promote(trials, cells, count, direction, rng, num_cells):
"""Sample a niche, take its best remaining trial, and fall back globally."""
remaining = set(range(len(trials)))
grouped = [[] for _ in range(num_cells)]
for i in sorted(remaining, key=lambda i: direction * trials[i].fitness):
grouped[cells[i]].append(i)
for _ in range(min(count, len(remaining))):
queue = grouped[rng.integers(num_cells)]
while queue and queue[-1] not in remaining:
queue.pop()
slot = queue.pop() if queue else int(rng.choice(sorted(remaining)))
remaining.remove(slot)
yield trials[slot].genome
## @brief Run cost-budgeted QD Hyperband with niche-level promotion.
[docs]
class QDHyperband:
"""Search designs over increasing evaluation fidelities.
:param archive: Best-only Grid or CVTGrid with one signed objective.
:param dimension: Number of real design coordinates.
:param fidelities: Increasing positive integer resource units. Rungs
are charged their total cost, including evaluations of promotions.
:param eta: Integer successive-halving factor, at least two.
:param ind_domain: Common lower and upper bounds for design coordinates.
:param seed: Private seed for new proposals and promotion.
"""
def __init__(self, archive, dimension, fidelities, *, eta=3, ind_domain=(0., 1.), seed=0):
if (type(archive) not in (Grid, CVTGrid) or archive.max_items_per_bin != 1
or archive.parents or archive.discard_random_on_bin_overload
or len(archive.fitness_domain or ()) != 1 or not archive.features_domain
or not archive.fitness_weights or len(archive.fitness_weights) != 1):
raise ValueError("Supply a parentless best-only Grid or CVTGrid with one configured objective.")
self.archive = archive
self.dimension = _positive_int(dimension, "dimension")
self.fidelities = tuple(_positive_int(cost, "fidelity") for cost in fidelities)
self.eta = _positive_int(eta, "eta")
if not self.fidelities or self.eta < 2 or any(a >= b for a, b in zip(self.fidelities, self.fidelities[1:])):
raise ValueError("Fidelities must strictly increase and eta must be at least two.")
self.ind_domain = _bounds(ind_domain)
self._direction = np.sign(archive.fitness_weights[0])
if self._direction not in (-1, 1) or not np.isfinite(archive.fitness_weights[0]):
raise ValueError("Provide a finite nonzero objective weight.")
self._rng = np.random.default_rng(seed)
self._cells = {cell: i for i, cell in enumerate(archive.solutions)}
self._trials = []
self._depth = len(self.fidelities) - 1
self._spent = 0
@property
def trials(self):
"""Return attempted evaluations in their submission order."""
return tuple(self._trials)
@property
def spent(self):
"""Return cumulative resource units including failed calls."""
return self._spent
def _propose(self, count, fidelity):
return self._rng.uniform(*self.ind_domain, size=(count, self.dimension))
def _measure(self, evaluate, genome, fidelity):
genome = tuple(map(float, genome))
self._spent += fidelity
outcome = evaluate(genome, fidelity)
if outcome is None:
row = FidelityTrial(genome, fidelity, None, None)
self._trials.append(row)
return row, None
fitness, descriptors = outcome
fitness = float(fitness)
descriptors = tuple(map(float, descriptors))
if not np.isfinite(fitness) or not np.isfinite(descriptors).all():
raise ValueError("Return finite fitness and descriptors or None for a failed measurement.")
row = FidelityTrial(genome, fidelity, fitness, descriptors)
self._trials.append(row)
try:
cell = self.archive.index_grid(descriptors)
except IndexError:
if len(descriptors) != len(self.archive.features_domain):
raise ValueError("The evaluator returned the wrong descriptor dimension.") from None
return row, None
if fidelity == self.fidelities[-1] and self.archive.in_bounds((fitness,), self.archive.fitness_domain):
individual = Individual(genome, fitness=Fitness((fitness,), weights=self.archive.fitness_weights),
features=Features(descriptors))
if self.archive.free > 0 or self.archive.solutions[cell]:
self.archive.add(individual)
return row, cell
## @brief Evaluate brackets while respecting an additional resource budget.
[docs]
def run(self, evaluate, budget):
"""Return the archive after spending at most budget additional units.
The evaluator accepts (genome, fidelity) and returns (scalar fitness,
descriptors) or None. Only results at the highest fidelity can enter
the reporting archive. A promotion uses its most recent descriptor.
"""
budget = _positive_int(budget, "budget")
stop = self._spent + budget
while stop - self._spent >= self.fidelities[-1]:
depth = self._depth
while depth >= 0:
schedule = _bracket(self.fidelities, self.eta, depth)
if sum(cost * count for cost, count in schedule) <= stop - self._spent:
break
depth -= 1
if depth < 0:
schedule = ((self.fidelities[-1], (stop - self._spent) // self.fidelities[-1]),)
self._depth = depth - 1 if depth > 0 else len(self.fidelities) - 1
genomes = self._propose(schedule[0][1], schedule[0][0])
for rung, (fidelity, _) in enumerate(schedule):
rows, cells = [], []
for genome in genomes:
row, cell = self._measure(evaluate, genome, fidelity)
if cell is not None:
rows.append(row)
cells.append(self._cells[cell])
if rung + 1 < len(schedule):
genomes = list(_promote(rows, cells, schedule[rung + 1][1], self._direction,
self._rng, len(self._cells)))
return self.archive
## @brief Augment quality-diversity Hyperband with fidelity-aware forest acquisition.
[docs]
class BOPElitesHyperband(QDHyperband):
"""Rank proposals by expected joint improvement over regular grid cells.
Forests train on all successful observations with the fidelity as an
input. Their predictions and incumbent comparisons use the first rung
of the planned bracket. A uniform fraction can be reserved for exploration.
:param quality_floor: Raw comparison value for a cell without observations.
:param model_after: Number of successful observations before fitting.
:param pool_size: Minimum number of candidates ranked at bracket start.
:param random_fraction: Fraction of each bracket reserved for uniform draws.
:param trees: Number of trees per output prediction.
:param kwargs: Arguments accepted by QDHyperband.
"""
def __init__(self, archive, dimension, fidelities, *, quality_floor, model_after=12,
pool_size=256, random_fraction=.1, trees=32, **kwargs):
super().__init__(archive, dimension, fidelities, **kwargs)
if type(archive) is not Grid or not np.isfinite(quality_floor) or not 0 <= random_fraction <= 1:
raise ValueError("Use a regular Grid, finite quality_floor and random_fraction in [0, 1].")
self._floor = self._direction * quality_floor
self._model_after = _positive_int(model_after, "model_after")
self._pool_size = _positive_int(pool_size, "pool_size")
self._trees = _positive_int(trees, "trees")
self._random_fraction = random_fraction
lower, upper = np.asarray(archive.features_domain).T
index = np.array(tuple(self._cells))
self._lower = lower + index / archive.shape * (upper - lower)
self._upper = lower + (index + 1) / archive.shape * (upper - lower)
self._closed = index + 1 == archive.shape
self.modelled_proposals = 0
def _propose(self, count, fidelity):
training = [row for row in self._trials if row.fitness is not None]
if len(training) < self._model_after or self._random_fraction == 1:
return super()._propose(count, fidelity)
def encode(genomes, levels):
return np.column_stack((genomes, np.asarray(levels) / self.fidelities[-1]))
fitted = RandomForestRegressor(n_estimators=self._trees,
random_state=int(self._rng.integers(2**32)))
fitted.fit(encode([row.genome for row in training], [row.fidelity for row in training]),
[(self._direction * row.fitness, *row.descriptors) for row in training])
incumbents = {}
for row in training:
if row.fidelity == fidelity:
try:
cell = self.archive.index_grid(row.descriptors)
except IndexError:
continue
if cell not in incumbents or self._direction * row.fitness > self._direction * incumbents[cell].fitness:
incumbents[cell] = row
pool = super()._propose(max(count, self._pool_size), fidelity)
if incumbents:
seeds = np.array([row.genome for row in incumbents.values()])
local = seeds[self._rng.integers(len(seeds), size=len(pool))]
pool = np.concatenate((pool, np.clip(local + self._rng.normal(
0., .1 * (self.ind_domain[1] - self.ind_domain[0]), local.shape), *self.ind_domain)))
points = encode(pool, np.full(len(pool), fidelity))
predictions = np.stack([tree.predict(points) for tree in fitted.estimators_])
mean, std = predictions.mean(axis=0), predictions.std(axis=0)
thresholds = np.array([self._floor if cell not in incumbents else self._direction * incumbents[cell].fitness
for cell in self._cells])
probability = _region_probabilities(mean[:, None, 1:], std[:, None, 1:],
self._lower, self._upper, self._closed)
acquisition = (probability * _expected_improvement(mean[:, :1], std[:, :1], thresholds)).sum(axis=1)
random_count = self._rng.binomial(count, self._random_fraction)
n = count - random_count
self.modelled_proposals += n
ranked = np.argsort(-acquisition, kind="stable")[:n]
return np.concatenate((pool[ranked], super()._propose(random_count, fidelity)))