QDpy
Loading...
Searching...
No Matches
hyperband.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Promote designs within descriptor niches using a hard resource budget."""
6
7from dataclasses import dataclass
8
9import numpy as np
10from sklearn.ensemble import RandomForestRegressor
11
12from qdpy.containers import CVTGrid, Grid
13from qdpy.phenotype import Features, Fitness, Individual
14from .bayesian import _expected_improvement, _region_probabilities
15from .modern import _bounds, _positive_int
16
17__all__ = ["QDHyperband", "BOPElitesHyperband", "FidelityTrial"]
18
19
20
21@dataclass(frozen=True)
23 """A failed evaluation has fitness and descriptors set to None."""
24
25 genome: tuple[float, ...]
26 fidelity: int
27 fitness: float | None
28 descriptors: tuple[float, ...] | None
29
30
31def _bracket(levels, eta, depth):
32 """Return the initial size and all successive-halving rungs."""
33 size = -(-(len(levels) * eta ** depth) // (depth + 1))
34 return tuple((level, size // eta ** rung) for rung, level in enumerate(levels[-depth - 1:]))
35
36
37def _promote(trials, cells, count, direction, rng, num_cells):
38 """Sample a niche, take its best remaining trial, and fall back globally."""
39 remaining = set(range(len(trials)))
40 grouped = [[] for _ in range(num_cells)]
41 for i in sorted(remaining, key=lambda i: direction * trials[i].fitness):
42 grouped[cells[i]].append(i)
43 for _ in range(min(count, len(remaining))):
44 queue = grouped[rng.integers(num_cells)]
45 while queue and queue[-1] not in remaining:
46 queue.pop()
47 slot = queue.pop() if queue else int(rng.choice(sorted(remaining)))
48 remaining.remove(slot)
49 yield trials[slot].genome
50
51
52
54 """Search designs over increasing evaluation fidelities.
55
56 :param archive: Best-only Grid or CVTGrid with one signed objective.
57 :param dimension: Number of real design coordinates.
58 :param fidelities: Increasing positive integer resource units. Rungs
59 are charged their total cost, including evaluations of promotions.
60 :param eta: Integer successive-halving factor, at least two.
61 :param ind_domain: Common lower and upper bounds for design coordinates.
62 :param seed: Private seed for new proposals and promotion.
63 """
64
65 def __init__(self, archive, dimension, fidelities, *, eta=3, ind_domain=(0., 1.), seed=0):
66 if (type(archive) not in (Grid, CVTGrid) or archive.max_items_per_bin != 1
67 or archive.parents or archive.discard_random_on_bin_overload
68 or len(archive.fitness_domain or ()) != 1 or not archive.features_domain
69 or not archive.fitness_weights or len(archive.fitness_weights) != 1):
70 raise ValueError("Supply a parentless best-only Grid or CVTGrid with one configured objective.")
71 self.archive = archive
72 self.dimension = _positive_int(dimension, "dimension")
73 self.fidelities = tuple(_positive_int(cost, "fidelity") for cost in fidelities)
74 self.eta = _positive_int(eta, "eta")
75 if not self.fidelities or self.eta < 2 or any(a >= b for a, b in zip(self.fidelities, self.fidelities[1:])):
76 raise ValueError("Fidelities must strictly increase and eta must be at least two.")
77 self.ind_domain = _bounds(ind_domain)
78 self._direction = np.sign(archive.fitness_weights[0])
79 if self._direction not in (-1, 1) or not np.isfinite(archive.fitness_weights[0]):
80 raise ValueError("Provide a finite nonzero objective weight.")
81 self._rng = np.random.default_rng(seed)
82 self._cells = {cell: i for i, cell in enumerate(archive.solutions)}
83 self._trials = []
84 self._depth = len(self.fidelities) - 1
85 self._spent = 0
86
87 @property
88 def trials(self):
89 """Return attempted evaluations in their submission order."""
90 return tuple(self._trials)
91
92 @property
93 def spent(self):
94 """Return cumulative resource units including failed calls."""
95 return self._spent
96
97 def _propose(self, count, fidelity):
98 return self._rng.uniform(*self.ind_domain, size=(count, self.dimension))
99
100 def _measure(self, evaluate, genome, fidelity):
101 genome = tuple(map(float, genome))
102 self._spent += fidelity
103 outcome = evaluate(genome, fidelity)
104 if outcome is None:
105 row = FidelityTrial(genome, fidelity, None, None)
106 self._trials.append(row)
107 return row, None
108 fitness, descriptors = outcome
109 fitness = float(fitness)
110 descriptors = tuple(map(float, descriptors))
111 if not np.isfinite(fitness) or not np.isfinite(descriptors).all():
112 raise ValueError("Return finite fitness and descriptors or None for a failed measurement.")
113 row = FidelityTrial(genome, fidelity, fitness, descriptors)
114 self._trials.append(row)
115 try:
116 cell = self.archive.index_grid(descriptors)
117 except IndexError:
118 if len(descriptors) != len(self.archive.features_domain):
119 raise ValueError("The evaluator returned the wrong descriptor dimension.") from None
120 return row, None
121 if fidelity == self.fidelities[-1] and self.archive.in_bounds((fitness,), self.archive.fitness_domain):
122 individual = Individual(genome, fitness=Fitness((fitness,), weights=self.archive.fitness_weights),
123 features=Features(descriptors))
124 if self.archive.free > 0 or self.archive.solutions[cell]:
125 self.archive.add(individual)
126 return row, cell
127
128
129 def run(self, evaluate, budget):
130 """Return the archive after spending at most budget additional units.
131
132 The evaluator accepts (genome, fidelity) and returns (scalar fitness,
133 descriptors) or None. Only results at the highest fidelity can enter
134 the reporting archive. A promotion uses its most recent descriptor.
135 """
136 budget = _positive_int(budget, "budget")
137 stop = self._spent + budget
138 while stop - self._spent >= self.fidelities[-1]:
139 depth = self._depth
140 while depth >= 0:
141 schedule = _bracket(self.fidelities, self.eta, depth)
142 if sum(cost * count for cost, count in schedule) <= stop - self._spent:
143 break
144 depth -= 1
145 if depth < 0:
146 schedule = ((self.fidelities[-1], (stop - self._spent) // self.fidelities[-1]),)
147 self._depth = depth - 1 if depth > 0 else len(self.fidelities) - 1
148 genomes = self._propose(schedule[0][1], schedule[0][0])
149 for rung, (fidelity, _) in enumerate(schedule):
150 rows, cells = [], []
151 for genome in genomes:
152 row, cell = self._measure(evaluate, genome, fidelity)
153 if cell is not None:
154 rows.append(row)
155 cells.append(self._cells[cell])
156 if rung + 1 < len(schedule):
157 genomes = list(_promote(rows, cells, schedule[rung + 1][1], self._direction,
158 self._rng, len(self._cells)))
159 return self.archive
160
161
162
164 """Rank proposals by expected joint improvement over regular grid cells.
165
166 Forests train on all successful observations with the fidelity as an
167 input. Their predictions and incumbent comparisons use the first rung
168 of the planned bracket. A uniform fraction can be reserved for exploration.
169
170 :param quality_floor: Raw comparison value for a cell without observations.
171 :param model_after: Number of successful observations before fitting.
172 :param pool_size: Minimum number of candidates ranked at bracket start.
173 :param random_fraction: Fraction of each bracket reserved for uniform draws.
174 :param trees: Number of trees per output prediction.
175 :param kwargs: Arguments accepted by QDHyperband.
176 """
177
178 def __init__(self, archive, dimension, fidelities, *, quality_floor, model_after=12,
179 pool_size=256, random_fraction=.1, trees=32, **kwargs):
180 super().__init__(archive, dimension, fidelities, **kwargs)
181 if type(archive) is not Grid or not np.isfinite(quality_floor) or not 0 <= random_fraction <= 1:
182 raise ValueError("Use a regular Grid, finite quality_floor and random_fraction in [0, 1].")
183 self._floor = self._direction * quality_floor
184 self._model_after = _positive_int(model_after, "model_after")
185 self._pool_size = _positive_int(pool_size, "pool_size")
186 self._trees = _positive_int(trees, "trees")
187 self._random_fraction = random_fraction
188 lower, upper = np.asarray(archive.features_domain).T
189 index = np.array(tuple(self._cells))
190 self._lower = lower + index / archive.shape * (upper - lower)
191 self._upper = lower + (index + 1) / archive.shape * (upper - lower)
192 self._closed = index + 1 == archive.shape
193 self.modelled_proposals = 0
194
195 def _propose(self, count, fidelity):
196 training = [row for row in self._trials if row.fitness is not None]
197 if len(training) < self._model_after or self._random_fraction == 1:
198 return super()._propose(count, fidelity)
199
200 def encode(genomes, levels):
201 return np.column_stack((genomes, np.asarray(levels) / self.fidelities[-1]))
202
203 fitted = RandomForestRegressor(n_estimators=self._trees,
204 random_state=int(self._rng.integers(2**32)))
205 fitted.fit(encode([row.genome for row in training], [row.fidelity for row in training]),
206 [(self._direction * row.fitness, *row.descriptors) for row in training])
207 incumbents = {}
208 for row in training:
209 if row.fidelity == fidelity:
210 try:
211 cell = self.archive.index_grid(row.descriptors)
212 except IndexError:
213 continue
214 if cell not in incumbents or self._direction * row.fitness > self._direction * incumbents[cell].fitness:
215 incumbents[cell] = row
216 pool = super()._propose(max(count, self._pool_size), fidelity)
217 if incumbents:
218 seeds = np.array([row.genome for row in incumbents.values()])
219 local = seeds[self._rng.integers(len(seeds), size=len(pool))]
220 pool = np.concatenate((pool, np.clip(local + self._rng.normal(
221 0., .1 * (self.ind_domain[1] - self.ind_domain[0]), local.shape), *self.ind_domain)))
222 points = encode(pool, np.full(len(pool), fidelity))
223 predictions = np.stack([tree.predict(points) for tree in fitted.estimators_])
224 mean, std = predictions.mean(axis=0), predictions.std(axis=0)
225 thresholds = np.array([self._floor if cell not in incumbents else self._direction * incumbents[cell].fitness
226 for cell in self._cells])
227 probability = _region_probabilities(mean[:, None, 1:], std[:, None, 1:],
228 self._lower, self._upper, self._closed)
229 acquisition = (probability * _expected_improvement(mean[:, :1], std[:, :1], thresholds)).sum(axis=1)
230 random_count = self._rng.binomial(count, self._random_fraction)
231 n = count - random_count
232 self.modelled_proposals += n
233 ranked = np.argsort(-acquisition, kind="stable")[:n]
234 return np.concatenate((pool[ranked], super()._propose(random_count, fidelity)))
Augment quality-diversity Hyperband with fidelity-aware forest acquisition.
Definition hyperband.py:163
One scheduled design measurement and the resource units it consumed.
Definition hyperband.py:22
Run cost-budgeted QD Hyperband with niche-level promotion.
Definition hyperband.py:53
run(self, evaluate, budget)
Evaluate brackets while respecting an additional resource budget.
Definition hyperband.py:129
_measure(self, evaluate, genome, fidelity)
Definition hyperband.py:100
_propose(self, count, fidelity)
Definition hyperband.py:97
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405