QDpy
Loading...
Searching...
No Matches
async_halving.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Schedule work without synchronous brackets and retain only full-fidelity elites."""
8
9import warnings
10from collections import Counter
11from dataclasses import dataclass
12from heapq import heappop, heappush
13from math import ceil
14
15import numpy as np
16
17from qdpy.base import generic_as_completed
18
19from .hyperband import FidelityTrial
20from .modern import _positive_int
21from .task_search import _measurement, _offer, _search_bounds, _validate_grid
22
23__all__ = ["AsyncQDHalving", "FidelityRequest"]
24
25
26
27@dataclass(frozen=True)
29 """An ask/tell ticket with its target fidelity and optional promotion source."""
30
31 id: int
32 genome: tuple[float, ...]
33 fidelity: int
34 promoted_from: int | None = None
35
36
37def _outcome(request, call, *args):
38 try:
39 return call(*args)
40 except Exception as error: # noqa: BLE001 - any worker failure consumes the priced trial.
41 warnings.warn(f"Fidelity evaluation {request.id} failed: {error}", stacklevel=3)
42 return None
43
44
45
47 """Run a descriptor-aware single-ladder adaptation of asynchronous halving.
48
49 Each group of eta completed requests at one rung unlocks a promotion
50 to the next rung. Eligible niches with fewer previous promotions go
51 first. Within that niche choose the best measured candidate. Reserve
52 the whole ladder's resources up front and charge each request in full.
53 When a rung cannot supply enough candidates, fill the next rung
54 with direct proposals. Only the highest fidelity populates the archive.
55
56 :param archive: Empty parentless best-only Grid or CVTGrid.
57 :param dimension: Number of real design coordinates.
58 :param fidelities: Strictly increasing positive integer resource costs.
59 :param budget: Total planned resource units, at least the highest cost.
60 :param eta: Minimum number of completed lower rung calls per promotion.
61 :param late_fraction: Fraction of promotion slots held until the
62 upstream rung finishes, so slower niches can still compete.
63 Keep at least one slot available to early results.
64 :param ind_domain: Common bounds for real coordinates.
65 :param propose: Optional callback (rng) for new genomes. By default
66 draw them uniformly within ind_domain.
67 :param seed: Seed for new proposals in scheduling order.
68 """
69
70 def __init__(self, archive, dimension, fidelities, *, budget, eta=3, late_fraction=.25,
71 ind_domain=(0., 1.), propose=None, seed=0):
72 _validate_grid(archive)
73 self.dimension = _positive_int(dimension, "dimension")
74 self.fidelities = tuple(_positive_int(cost, "fidelity") for cost in fidelities)
75 self.budget = _positive_int(budget, "budget")
76 self.eta = _positive_int(eta, "eta")
77 if (not self.fidelities or self.eta < 2
78 or any(a >= b for a, b in zip(self.fidelities, self.fidelities[1:]))):
79 raise ValueError("Fidelities must strictly increase and eta must be at least two.")
80 if self.budget < self.fidelities[-1] or (propose is not None and not callable(propose)):
81 raise ValueError("Budget must buy a full-fidelity trial. Use a callable proposal operator.")
82 if not 0. <= late_fraction <= 1.:
83 raise ValueError("late_fraction must be in [0, 1].")
84 self.ind_domain = _search_bounds(ind_domain)
85 if archive.fitness_weights is None:
86 archive._set_fitness_weights((1.,))
87 self.archive = archive
88 self._direction = np.sign(archive.fitness_weights[0])
89 self._propose = propose
90 self._rng = np.random.default_rng(seed)
91 counts = [self.eta ** power for power in reversed(range(len(self.fidelities)))]
92 cycle_cost = sum(count * fidelity for count, fidelity in zip(counts, self.fidelities))
93 cycles, extra = divmod(self.budget, cycle_cost)
94 counts = [count * cycles for count in counts]
95 counts[-1] += extra // self.fidelities[-1]
96 self._quotas = tuple(counts)
97 self._early = tuple(max(1, slots - ceil(late_fraction * slots))
98 for slots in (count // self.eta for count in counts[:-1]))
99 self._started = [0] * len(counts)
100 self._completed = [0] * len(counts)
101 self._queues = [{} for _ in counts[:-1]]
102 self._by_cell = [Counter() for _ in counts[:-1]]
103 self._promoted = [0] * len(counts)
104 self._pending = {}
105 self._trials = []
106 self._spent = 0
107 self._reserved = 0
108 self._next_id = 0
109
110 @property
111 def quotas(self):
112 """Return the number of evaluation slots budgeted at each fidelity."""
113 return self._quotas
114
115 @property
116 def pending(self):
117 """Return outstanding tickets in submission order."""
118 return tuple(request for request, _ in self._pending.values())
119
120 @property
121 def trials(self):
122 """Return attempted measurements in the order accepted by tell."""
123 return tuple(self._trials)
124
125 @property
126 def spent(self):
127 """Return completed resource units, including failed evaluations."""
128 return self._spent
129
130 @property
131 def reserved(self):
132 """Return resource units assigned to outstanding tickets."""
133 return self._reserved
134
135 def _new_genome(self):
136 if self._propose is None:
137 return tuple(map(float, self._rng.uniform(*self.ind_domain, size=self.dimension)))
138 genome = tuple(map(float, self._propose(self._rng)))
139 if len(genome) != self.dimension or not all(
140 self.ind_domain[0] <= value <= self.ind_domain[1] for value in genome):
141 raise ValueError("A proposal must have the configured dimension and stay within bounds.")
142 return genome
143
144 def _promote(self, source):
145 queues, counts = self._queues[source], self._by_cell[source]
146 unlocked = self._completed[source] // self.eta
147 if self._completed[source] < self._quotas[source]:
148 unlocked = min(unlocked, self._early[source])
149 if self._promoted[source + 1] >= unlocked or not queues:
150 return None
151 cell = min(queues, key=lambda candidate: (counts[candidate], queues[candidate][0][1]))
152 _, _, parent = heappop(queues[cell])
153 if not queues[cell]:
154 del queues[cell]
155 counts[cell] += 1
156 self._promoted[source + 1] += 1
157 return parent
158
159
160 def ask(self):
161 """Schedule the deepest ready promotion before starting new designs.
162
163 A None result with pending tickets means more completions are needed.
164 With no pending tickets, the planned evaluation slots are exhausted.
165 Call ask and tell from the same coordinator.
166 """
167 for rung in reversed(range(len(self._quotas))):
168 if self._started[rung] >= self._quotas[rung]:
169 continue
170 parent = self._promote(rung - 1) if rung else None
171 if parent is None and rung and self._completed[rung - 1] < self._quotas[rung - 1]:
172 continue
173 genome = parent.genome if parent is not None else self._new_genome()
174 request = FidelityRequest(self._next_id, genome, self.fidelities[rung],
175 parent.id if parent is not None else None)
176 self._pending[request.id] = request, rung
177 self._next_id += 1
178 self._started[rung] += 1
179 self._reserved += request.fidelity
180 return request
181 return None
182
183
184 def tell(self, request, result):
185 """Record (scalar fitness, descriptors) or a failed evaluation (None).
186
187 Pass back the ticket returned by ask. A malformed measurement raises
188 and leaves the ticket pending so the caller can correct it or record
189 a failure. Valid measurements outside the archive domain are charged.
190 """
191 if (not isinstance(request, FidelityRequest) or request.id not in self._pending
192 or self._pending[request.id][0] is not request):
193 raise ValueError("Return an outstanding request from this scheduler exactly once.")
194 _, rung = self._pending[request.id]
195 if result is None:
196 row = FidelityTrial(request.genome, request.fidelity, None, None)
197 else:
198 fitness, descriptors = result
199 candidate, cell = _measurement(self.archive, ((fitness,), descriptors), request.genome)
200 row = FidelityTrial(request.genome, request.fidelity, candidate.fitness.values[0],
201 tuple(candidate.features.values))
202 if rung == len(self.fidelities) - 1:
203 _offer(self.archive, (candidate, cell))
204 elif cell is not None:
205 queue = self._queues[rung].setdefault(cell, [])
206 heappush(queue, (-self._direction * row.fitness, request.id, request))
207 del self._pending[request.id]
208 self._completed[rung] += 1
209 self._reserved -= request.fidelity
210 self._spent += request.fidelity
211 self._trials.append(row)
212 return row
213
214
215 def run(self, evaluate, *, executor=None, max_pending=1):
216 """Use evaluate(genome, fidelity) and return the full-fidelity archive.
217
218 With a QDpy-supported executor consume first completions and
219 dispatch new requests up to max_pending at a time.
220 Evaluator exceptions are warned and charged as failed attempts.
221 The caller owns the executor's lifetime.
222 """
223 if self._pending:
224 raise RuntimeError("Finish the outstanding ask/tell tickets before calling run.")
225 if not callable(evaluate):
226 raise TypeError("Supply a callable evaluator.")
227 limit = _positive_int(max_pending, "max_pending")
228 futures = {}
229 try:
230 if executor is None:
231 while (request := self.ask()) is not None:
232 self.tell(request, _outcome(request, evaluate, request.genome, request.fidelity))
233 return self.archive
234 while True:
235 while len(futures) < limit and (request := self.ask()) is not None:
236 future = executor.submit(evaluate, request.genome, request.fidelity)
237 futures[future] = request
238 if not futures:
239 break
240 future = generic_as_completed(tuple(futures))
241 request = futures.pop(future)
242 self.tell(request, _outcome(request, future.result))
243 finally:
244 for future in futures:
245 future.cancel()
246 for request in self.pending:
247 self.tell(request, None)
248 return self.archive
Allocate fixed rung resources and promote by the latest measured niche.
ask(self)
Reserve and return a ready evaluation, or return None.
tell(self, request, result)
Accept an outcome and release any promotions it enables.
run(self, evaluate, *, executor=None, max_pending=1)
Run the scheduler sequentially or with a caller-owned executor.
A reserved evaluation that the coordinator can dispatch.
One scheduled design measurement and the resource units it consumed.
Definition hyperband.py:22