21from .task_search
import _measurement, _offer, _search_bounds, _validate_grid
47 """Run a descriptor-aware single-ladder adaptation of asynchronous halving.
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.
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.
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")
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].")
85 if archive.fitness_weights
is None:
86 archive._set_fitness_weights((1.,))
88 self.
_direction = np.sign(archive.fitness_weights[0])
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]
97 self.
_early = tuple(max(1, slots - ceil(late_fraction * slots))
98 for slots
in (count // self.
eta for count
in counts[:-1]))
101 self.
_queues = [{}
for _
in counts[:-1]]
102 self.
_by_cell = [Counter()
for _
in counts[:-1]]
112 """Return the number of evaluation slots budgeted at each fidelity."""
117 """Return outstanding tickets in submission order."""
118 return tuple(request
for request, _
in self.
_pending.values())
122 """Return attempted measurements in the order accepted by tell."""
127 """Return completed resource units, including failed evaluations."""
132 """Return resource units assigned to outstanding tickets."""
135 def _new_genome(self):
139 if len(genome) != self.
dimension or not all(
141 raise ValueError(
"A proposal must have the configured dimension and stay within bounds.")
144 def _promote(self, source):
148 unlocked = min(unlocked, self.
_early[source])
149 if self.
_promoted[source + 1] >= unlocked
or not queues:
151 cell = min(queues, key=
lambda candidate: (counts[candidate], queues[candidate][0][1]))
152 _, _, parent = heappop(queues[cell])
161 """Schedule the deepest ready promotion before starting new designs.
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.
167 for rung
in reversed(range(len(self.
_quotas))):
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]:
173 genome = parent.genome
if parent
is not None else self.
_new_genome()
175 parent.id
if parent
is not None else None)
176 self.
_pending[request.id] = request, rung
184 def tell(self, request, result):
185 """Record (scalar fitness, descriptors) or a failed evaluation (None).
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.
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.")
196 row =
FidelityTrial(request.genome, request.fidelity,
None,
None)
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))
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))
210 self.
_spent += request.fidelity
215 def run(self, evaluate, *, executor=None, max_pending=1):
216 """Use evaluate(genome, fidelity) and return the full-fidelity archive.
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.
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")
231 while (request := self.
ask())
is not None:
232 self.
tell(request, _outcome(request, evaluate, request.genome, request.fidelity))
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
240 future = generic_as_completed(tuple(futures))
241 request = futures.pop(future)
242 self.
tell(request, _outcome(request, future.result))
244 for future
in futures:
247 self.
tell(request,
None)