# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Completion-driven successive halving by descriptor niche.
# @see https://doi.org/10.48550/arXiv.2106.12639
# @see https://doi.org/10.48550/arXiv.2208.00204
"""Schedule work without synchronous brackets and retain only full-fidelity elites."""
import warnings
from collections import Counter
from dataclasses import dataclass
from heapq import heappop, heappush
from math import ceil
import numpy as np
from qdpy.base import generic_as_completed
from .hyperband import FidelityTrial
from .modern import _positive_int
from .task_search import _measurement, _offer, _search_bounds, _validate_grid
__all__ = ["AsyncQDHalving", "FidelityRequest"]
## @brief A reserved evaluation that the coordinator can dispatch.
[docs]
@dataclass(frozen=True)
class FidelityRequest:
"""An ask/tell ticket with its target fidelity and optional promotion source."""
id: int
genome: tuple[float, ...]
fidelity: int
promoted_from: int | None = None
def _outcome(request, call, *args):
try:
return call(*args)
except Exception as error: # noqa: BLE001 - any worker failure consumes the priced trial.
warnings.warn(f"Fidelity evaluation {request.id} failed: {error}", stacklevel=3)
return None
## @brief Allocate fixed rung resources and promote by the latest measured niche.
[docs]
class AsyncQDHalving:
"""Run a descriptor-aware single-ladder adaptation of asynchronous halving.
Each group of eta completed requests at one rung unlocks a promotion
to the next rung. Eligible niches with fewer previous promotions go
first. Within that niche choose the best measured candidate. Reserve
the whole ladder's resources up front and charge each request in full.
When a rung cannot supply enough candidates, fill the next rung
with direct proposals. Only the highest fidelity populates the archive.
:param archive: Empty parentless best-only Grid or CVTGrid.
:param dimension: Number of real design coordinates.
:param fidelities: Strictly increasing positive integer resource costs.
:param budget: Total planned resource units, at least the highest cost.
:param eta: Minimum number of completed lower rung calls per promotion.
:param late_fraction: Fraction of promotion slots held until the
upstream rung finishes, so slower niches can still compete.
Keep at least one slot available to early results.
:param ind_domain: Common bounds for real coordinates.
:param propose: Optional callback (rng) for new genomes. By default
draw them uniformly within ind_domain.
:param seed: Seed for new proposals in scheduling order.
"""
def __init__(self, archive, dimension, fidelities, *, budget, eta=3, late_fraction=.25,
ind_domain=(0., 1.), propose=None, seed=0):
_validate_grid(archive)
self.dimension = _positive_int(dimension, "dimension")
self.fidelities = tuple(_positive_int(cost, "fidelity") for cost in fidelities)
self.budget = _positive_int(budget, "budget")
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.")
if self.budget < self.fidelities[-1] or (propose is not None and not callable(propose)):
raise ValueError("Budget must buy a full-fidelity trial. Use a callable proposal operator.")
if not 0. <= late_fraction <= 1.:
raise ValueError("late_fraction must be in [0, 1].")
self.ind_domain = _search_bounds(ind_domain)
if archive.fitness_weights is None:
archive._set_fitness_weights((1.,))
self.archive = archive
self._direction = np.sign(archive.fitness_weights[0])
self._propose = propose
self._rng = np.random.default_rng(seed)
counts = [self.eta ** power for power in reversed(range(len(self.fidelities)))]
cycle_cost = sum(count * fidelity for count, fidelity in zip(counts, self.fidelities))
cycles, extra = divmod(self.budget, cycle_cost)
counts = [count * cycles for count in counts]
counts[-1] += extra // self.fidelities[-1]
self._quotas = tuple(counts)
self._early = tuple(max(1, slots - ceil(late_fraction * slots))
for slots in (count // self.eta for count in counts[:-1]))
self._started = [0] * len(counts)
self._completed = [0] * len(counts)
self._queues = [{} for _ in counts[:-1]]
self._by_cell = [Counter() for _ in counts[:-1]]
self._promoted = [0] * len(counts)
self._pending = {}
self._trials = []
self._spent = 0
self._reserved = 0
self._next_id = 0
@property
def quotas(self):
"""Return the number of evaluation slots budgeted at each fidelity."""
return self._quotas
@property
def pending(self):
"""Return outstanding tickets in submission order."""
return tuple(request for request, _ in self._pending.values())
@property
def trials(self):
"""Return attempted measurements in the order accepted by tell."""
return tuple(self._trials)
@property
def spent(self):
"""Return completed resource units, including failed evaluations."""
return self._spent
@property
def reserved(self):
"""Return resource units assigned to outstanding tickets."""
return self._reserved
def _new_genome(self):
if self._propose is None:
return tuple(map(float, self._rng.uniform(*self.ind_domain, size=self.dimension)))
genome = tuple(map(float, self._propose(self._rng)))
if len(genome) != self.dimension or not all(
self.ind_domain[0] <= value <= self.ind_domain[1] for value in genome):
raise ValueError("A proposal must have the configured dimension and stay within bounds.")
return genome
def _promote(self, source):
queues, counts = self._queues[source], self._by_cell[source]
unlocked = self._completed[source] // self.eta
if self._completed[source] < self._quotas[source]:
unlocked = min(unlocked, self._early[source])
if self._promoted[source + 1] >= unlocked or not queues:
return None
cell = min(queues, key=lambda candidate: (counts[candidate], queues[candidate][0][1]))
_, _, parent = heappop(queues[cell])
if not queues[cell]:
del queues[cell]
counts[cell] += 1
self._promoted[source + 1] += 1
return parent
## @brief Reserve and return a ready evaluation, or return None.
[docs]
def ask(self):
"""Schedule the deepest ready promotion before starting new designs.
A None result with pending tickets means more completions are needed.
With no pending tickets, the planned evaluation slots are exhausted.
Call ask and tell from the same coordinator.
"""
for rung in reversed(range(len(self._quotas))):
if self._started[rung] >= self._quotas[rung]:
continue
parent = self._promote(rung - 1) if rung else None
if parent is None and rung and self._completed[rung - 1] < self._quotas[rung - 1]:
continue
genome = parent.genome if parent is not None else self._new_genome()
request = FidelityRequest(self._next_id, genome, self.fidelities[rung],
parent.id if parent is not None else None)
self._pending[request.id] = request, rung
self._next_id += 1
self._started[rung] += 1
self._reserved += request.fidelity
return request
return None
## @brief Accept an outcome and release any promotions it enables.
[docs]
def tell(self, request, result):
"""Record (scalar fitness, descriptors) or a failed evaluation (None).
Pass back the ticket returned by ask. A malformed measurement raises
and leaves the ticket pending so the caller can correct it or record
a failure. Valid measurements outside the archive domain are charged.
"""
if (not isinstance(request, FidelityRequest) or request.id not in self._pending
or self._pending[request.id][0] is not request):
raise ValueError("Return an outstanding request from this scheduler exactly once.")
_, rung = self._pending[request.id]
if result is None:
row = FidelityTrial(request.genome, request.fidelity, None, None)
else:
fitness, descriptors = result
candidate, cell = _measurement(self.archive, ((fitness,), descriptors), request.genome)
row = FidelityTrial(request.genome, request.fidelity, candidate.fitness.values[0],
tuple(candidate.features.values))
if rung == len(self.fidelities) - 1:
_offer(self.archive, (candidate, cell))
elif cell is not None:
queue = self._queues[rung].setdefault(cell, [])
heappush(queue, (-self._direction * row.fitness, request.id, request))
del self._pending[request.id]
self._completed[rung] += 1
self._reserved -= request.fidelity
self._spent += request.fidelity
self._trials.append(row)
return row
## @brief Run the scheduler sequentially or with a caller-owned executor.
[docs]
def run(self, evaluate, *, executor=None, max_pending=1):
"""Use evaluate(genome, fidelity) and return the full-fidelity archive.
With a QDpy-supported executor consume first completions and
dispatch new requests up to max_pending at a time.
Evaluator exceptions are warned and charged as failed attempts.
The caller owns the executor's lifetime.
"""
if self._pending:
raise RuntimeError("Finish the outstanding ask/tell tickets before calling run.")
if not callable(evaluate):
raise TypeError("Supply a callable evaluator.")
limit = _positive_int(max_pending, "max_pending")
futures = {}
try:
if executor is None:
while (request := self.ask()) is not None:
self.tell(request, _outcome(request, evaluate, request.genome, request.fidelity))
return self.archive
while True:
while len(futures) < limit and (request := self.ask()) is not None:
future = executor.submit(evaluate, request.genome, request.fidelity)
futures[future] = request
if not futures:
break
future = generic_as_completed(tuple(futures))
request = futures.pop(future)
self.tell(request, _outcome(request, future.result))
finally:
for future in futures:
future.cancel()
for request in self.pending:
self.tell(request, None)
return self.archive