QDpy
Loading...
Searching...
No Matches
mcbo_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""A fixed-inducing-point MCBO-Elites variant with native Grid and CVT admission."""
8
9from dataclasses import dataclass
10from time import perf_counter
11
12import numpy as np
13from scipy.linalg import cholesky, cho_solve, solve_triangular
14from scipy.spatial.distance import cdist
15from scipy.stats import qmc
16
17from qdpy.base import registry
18from qdpy.containers import CVTGrid, Grid
19from .modern import _bounds, _FixedGeneration, _positive_int
20
21__all__ = ["MCBOElites", "MCBOStats"]
22
23
25 """Optimal Gaussian variational posterior with fixed whitened inducing features.
26
27 For feature matrix Phi and normalized outputs Y, accumulate
28 I + Phi.T @ Phi / noise and Phi.T @ Y / noise. The expected likelihood
29 also contains a residual prior variance term independent of q(u).
30 Keep this variance in predictions. All outputs share the same kernel
31 and observation noise but have independent inducing posteriors.
32 """
33
34 def __init__(self, inducing, output_size, *, lengthscale, noise):
35 self.inducing = np.array(inducing, dtype=float, copy=True)
36 self.lengthscale, self.noise = lengthscale, noise
37 kernel = self._kernel(self.inducing, self.inducing)
38 kernel.flat[::len(kernel) + 1] += 1e-9
39 self._prior = cholesky(kernel, lower=True)
40 self._precision = np.eye(len(kernel))
41 self._information = np.zeros((len(kernel), output_size))
42 self._factor = self._precision.copy()
43 self._weights = self._information.copy()
44 self.n_observations = 0
45
46 def _kernel(self, first, second):
47 with np.errstate(over="ignore"):
48 return np.exp(-.5 * np.square(cdist(first, second) / self.lengthscale))
49
50 def _features(self, points):
51 return solve_triangular(self._prior, self._kernel(self.inducing, points), lower=True,
52 check_finite=False)
53
54 def update(self, points, outputs):
55 features = self._features(points)
56 precision = self._precision + features @ features.T / self.noise
57 information = self._information + features @ outputs / self.noise
58 if not np.isfinite(information).all() or not np.isfinite(precision).all():
59 raise ValueError("Nonfinite sparse GP statistics. Increase output scaling or noise.")
60 factor = cholesky(precision, lower=True)
61 weights = cho_solve((factor, True), information)
62 self._precision, self._information = precision, information
63 self._factor, self._weights = factor, weights
64 self.n_observations += len(points)
65
66 def predict(self, points):
67 features = self._features(points)
68 conditional = np.maximum(0., 1. - np.square(features).sum(axis=0))
69 projected = solve_triangular(self._factor, features, lower=True, check_finite=False)
70 variance = conditional + np.square(projected).sum(axis=0)
71 return features.T @ self._weights, np.sqrt(variance)
72
73
74
75@dataclass(frozen=True)
77 """Wall times cover online model work and model-based proposal selection."""
78
79 evaluations: int
80 observations: int
81 archive_updates: int
82 model_updates: int
83 model_seconds: float
84 acquisition_seconds: float
85
86
87
88@registry.register
90 """Fit a fixed-budget surrogate incrementally and archive actual measurements.
91
92 Independent objective and descriptor posteriors use shared sparse
93 kernel features. For each candidate, sample the outputs and determine
94 the actual cell of each sampled descriptor. Average improvement over
95 those draws, with zero credit outside the descriptor domain. For a
96 batch, rank a single candidate pool against a frozen archive and
97 evaluate distinct proposals in order. Observation noise is used for
98 fitting. Acquisition draws are from the latent predictive distribution.
99
100 :param container: Parentless best-only Grid or CVTGrid with finite descriptor intervals.
101 :param budget: Managed-run budget in attempted true evaluations.
102 :param dimension: Number of bounded real decision variables.
103 :param ind_domain: Shared lower and upper decision bounds.
104 :param quality_floor: Improvement baseline for empty cells in signed fitness units.
105 :param quality_scale: Positive scale for objective observations in signed fitness units.
106 :param inducing_points: Number of fixed Sobol inducing points in decision space.
107 :param lengthscale: RBF length scale in normalized decision coordinates.
108 :param noise: Observation noise variance in normalized output coordinates.
109 :param initial_samples: Uniform Sobol initialization budget.
110 :param candidate_pool: Number of Sobol candidates scored per model-based generation.
111 :param posterior_samples: Monte Carlo draws per candidate.
112 :param batch_size: Maximum in-flight evaluations per generation.
113 :param seed: Private proposal and acquisition seed.
114 :param kwargs: Native optimiser options.
115 """
116
117 _requires_proposed_genome = True
118
119 def __init__(self, container, budget, dimension, ind_domain, quality_floor, *, quality_scale=1.,
120 inducing_points=32, lengthscale=.25, noise=.01, initial_samples=None, candidate_pool=128,
121 posterior_samples=64, batch_size=1, seed=0, **kwargs):
122 if (type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1 or container.parents
123 or container.discard_random_on_bin_overload or len(container.fitness_domain or ()) != 1
124 or not len(container.features_domain) or container.fitness_score_names or container.features_score_names):
125 raise ValueError("Supply a parentless best-only Grid or CVTGrid with direct single-objective scores.")
126 lower, upper = np.asarray(container.features_domain, dtype=float).T
127 widths = upper - lower
128 if not (np.isfinite(lower).all() and np.isfinite(upper).all()
129 and np.isfinite(widths).all() and (widths > 0).all()):
130 raise ValueError("Use finite positive descriptor intervals and widths.")
131 if not (np.isfinite(quality_floor) and 0 < quality_scale < np.inf
132 and 0 < lengthscale < np.inf and np.finfo(float).eps <= noise < np.inf):
133 raise ValueError("Use a finite quality floor, positive scales, and noise of at least machine epsilon.")
134 self.ind_domain = _bounds(ind_domain)
135 if not np.isfinite(self.ind_domain[1] - self.ind_domain[0]):
136 raise ValueError("Use a finite decision interval width.")
137 dimension = _positive_int(dimension, "dimension")
138 self._inducing_count = _positive_int(inducing_points, "inducing_points")
139 self._batch_limit = _positive_int(batch_size, "batch_size")
140 self._pool_size = _positive_int(candidate_pool, "candidate_pool")
141 if self._pool_size < self._batch_limit:
142 raise ValueError("candidate_pool must be at least batch_size.")
143 self._initial = (max(2, dimension * 4) if initial_samples is None
144 else _positive_int(initial_samples, "initial_samples"))
145 self._sample_count = _positive_int(posterior_samples, "posterior_samples")
146 self._lengthscale, self._noise = lengthscale, noise
147 self._quality_floor, self.seed = quality_floor, seed
148 self._lower, self._upper = lower, upper
149 self._scales = np.r_[quality_scale, widths]
150 self._offsets = np.r_[quality_floor, lower + .5 * widths]
151 self._cells = tuple(container.solutions)
152 self._shape = np.asarray(container.shape, dtype=int)
153 if container.fitness_weights is not None:
154 kwargs.setdefault("optimisation_task", container.fitness_weights)
155 super().__init__(container, _positive_int(budget, "budget"), dimension=dimension,
156 batch_size=self._batch_limit, **kwargs)
157
158 def reinit(self):
159 """Reset the model, deterministic proposal streams, and statistics."""
160 super().reinit()
161 basis, samples = np.random.SeedSequence(self.seed).spawn(2)
162 self._sobol = qmc.Sobol(self.dimension, scramble=True, seed=self.seed)
163 self._basis = qmc.Sobol(self.dimension, scramble=True, seed=np.random.default_rng(basis))
164 rng = np.random.default_rng(samples)
165 self._draws = rng.normal(size=(self._sample_count, len(self._scales)))
166 self._model = None
167 self._model_updates = 0
168 self._model_seconds = self._acquisition_seconds = 0.
169 self._seen = set()
170 self._batch_points = None
171
172 @property
173 def stats(self):
174 """Return cumulative evaluation counts and compute times."""
175 observations = 0 if self._model is None else self._model.n_observations
176 return MCBOStats(self.nb_evaluations, observations, self.nb_updated, self._model_updates,
178
179 def _start_fixed_batch(self, size):
180 super()._start_fixed_batch(size)
181 self._batch_points = None
182
183 def _raw_point(self, point):
184 lower, upper = self.ind_domain
185 return lower + (upper - lower) * point
186
187 def _pool(self, count):
188 # Keep all proposals in one batch distinct after rescaling into decision coordinates.
189 candidates = {}
190 for _ in range(count + 1024):
191 point = self._sobol.random(1)[0]
192 key = tuple(self._raw_point(point))
193 if key in self._seen:
194 continue
195 candidates.setdefault(key, point)
196 if len(candidates) == count:
197 return np.asarray(list(candidates.values()))
198 if len(candidates) >= self._pending_size:
199 return np.asarray(list(candidates.values()))
200 raise RuntimeError("The Sobol stream could not find enough distinct genomes in the decision domain.")
201
202 def _thresholds(self):
203 weights = self.container.fitness_weights
204 return np.asarray([self.container.get_ind_fitness(self.container.solutions[cell][0]).values[0] * weights[0]
205 if self.container.solutions[cell] else self._quality_floor for cell in self._cells])
206
207 def _improvement(self, draws):
208 descriptors = draws[..., 1:].reshape(-1, len(self._lower))
209 valid = ((descriptors >= self._lower) & (descriptors <= self._upper)).all(axis=1)
210 values = descriptors[valid]
211 if isinstance(self.container, CVTGrid):
212 centers = self.container.cluster_centers
213 block = max(1, (1 << 18) // len(centers))
214 cells = np.empty(len(values), dtype=int)
215 for offset in range(0, len(values), block):
216 rows = values[offset:offset + block]
217 distances = cdist(rows, centers)
218 closest = distances.argmin(axis=1)
219 minimum = distances[np.arange(len(rows)), closest]
220 for i in np.flatnonzero(~np.isfinite(minimum) | (minimum < np.sqrt(np.finfo(float).tiny))):
221 if minimum[i] != 0. or not np.array_equal(rows[i], centers[closest[i]]):
222 closest[i], = self.container.index_grid(tuple(rows[i]))
223 cells[offset:offset + block] = closest
224 else:
225 indices = (values - self._lower) / (self._scales[1:] / self._shape)
226 indices = np.minimum(self._shape - 1, indices.astype(np.intp))
227 cells = np.ravel_multi_index(indices.T, self.container.shape)
228 improvement = np.zeros(len(descriptors))
229 improvement[valid] = np.maximum(draws[..., 0].ravel()[valid] - self._thresholds()[cells], 0.)
230 return improvement.reshape(draws.shape[:-1]).mean(axis=1)
231
232 def _internal_ask(self, base_ind):
233 if self._batch_points is None:
234 observations = 0 if self._model is None else self._model.n_observations
235 if self.nb_suggestions < self._initial or observations < 2:
236 self._batch_points = self._pool(self._pending_size)
237 else:
238 start = perf_counter()
239 pool = self._pool(self._pool_size)
240 means, deviations = self._model.predict(pool)
241 draws = (means[:, None, :] + deviations[:, None, None] * self._draws)
242 draws = draws * self._scales + self._offsets
243 ranking = np.argsort(-self._improvement(draws), kind="stable")
244 self._batch_points = pool[ranking[:self._pending_size]]
245 self._acquisition_seconds += perf_counter() - start
246 base_ind[:] = self._raw_point(self._batch_points[len(self._issued)])
247 self._seen.add(tuple(base_ind))
248 return base_ind
249
250 def _check_candidate(self, individual):
251 self._check_measurements(individual)
252 fitness = self.container.get_ind_fitness(individual).values
253 descriptors = tuple(self.container.get_ind_features(individual))
254 if (len(fitness) != 1 or not np.isfinite(fitness[0] * self.container.fitness_weights[0])
255 or len(descriptors) != len(self._lower)):
256 raise ValueError("Use one finite signed objective and matching descriptors.")
257
258 def _commit_generation(self, evaluated):
259 indices = [i for i, row in enumerate(evaluated) if row is not None]
260 if not indices:
261 return set()
262 start = perf_counter()
263 container = self.container
264 values = np.asarray([(container.get_ind_fitness(evaluated[i]).values[0] * container.fitness_weights[0],
265 *container.get_ind_features(evaluated[i])) for i in indices])
266 normalized = (values - self._offsets) / self._scales
267 if not np.isfinite(normalized).all():
268 raise ValueError("Surrogate observations must be finite after scaling.")
269 if self._model is None:
270 points = self._basis.random_base2((self._inducing_count - 1).bit_length())[:self._inducing_count]
271 self._model = _OnlineSparseGP(points, len(self._scales), lengthscale=self._lengthscale, noise=self._noise)
272 self._model.update(self._batch_points[indices], normalized)
273 self._model_updates += 1
274 self._model_seconds += perf_counter() - start
275
276 admitted = set()
277 for i in indices:
278 candidate = evaluated[i]
279 descriptors = tuple(container.get_ind_features(candidate))
280 if (container.in_bounds(descriptors, container.features_domain)
281 and container.in_bounds(container.get_ind_fitness(candidate).values, container.fitness_domain)
282 and self._offer_to_grid(candidate, container.index_grid(descriptors))):
283 admitted.add(i)
284 return admitted
Optimize sampled expected improvement over actual descriptor cells.
Report true measurements, model updates, and separate compute costs.
_check_measurements(self, individual)
Definition modern.py:216
_offer_to_grid(self, individual, cell)
Definition modern.py:228