QDpy
Loading...
Searching...
No Matches
differentiable.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""CMA-MAEGA with separate centre and offspring evaluation phases."""
6
7from dataclasses import dataclass
8from math import isfinite
9from typing import Sequence
10import warnings
11
12import numpy as np
13
14from qdpy.base import registry
15from .constrained import _validate_grid
16from .modern import CMAMAE
17
18__all__ = ["GradientEvaluation", "CMAMAEGA", "CMAMEGA"]
19
20
21
22@dataclass(frozen=True)
24 """Measurements from a single gradient evaluation.
25
26 The Jacobian has one row for the objective followed by a row for each
27 descriptor. Columns follow the order of the genome coordinates.
28 """
29
30 fitness: float
31 descriptors: Sequence[float]
32 jacobian: np.ndarray
33
34
35def _gradient_basis(jacobian, objective_weight):
36 # Scale rows before taking norms so very large or small derivatives
37 # retain their direction without overflow or underflow.
38 scale = np.max(np.abs(jacobian), axis=1, keepdims=True)
39 rows = np.divide(jacobian, scale, out=np.zeros_like(jacobian), where=scale != 0)
40 rows[0] *= np.sign(objective_weight)
41 norms = np.linalg.norm(rows, axis=1, keepdims=True)
42 return np.divide(rows, norms, out=rows, where=norms != 0)
43
44
45
46@registry.register
48 """CMA-MAE with a gradient arborescence over the current centre.
49
50 Install the optional ``cma`` extra. Each centre evaluation consumes one
51 candidate slot. Subsequent offspring use the ordinary QDpy evaluator.
52 The centre and offspring batches each emit an iteration callback.
53
54 :param gradient_evaluate: Callable returning a GradientEvaluation.
55 :param step_size: Multiplier for the rank-weighted centre displacement.
56 :param sigma0: Initial step size in gradient coefficient coordinates.
57 :param kwargs: CMA-MAE options, including the reporting grid, bounds,
58 budget, initial point, batch size, threshold and archive learning rate.
59 """
60
61 def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *,
62 gradient_evaluate, step_size=1.0, **kwargs):
63 if not callable(gradient_evaluate):
64 raise TypeError("gradient_evaluate must be callable.")
65 if not 0 < step_size < np.inf:
66 raise ValueError("step_size must be finite and positive.")
67 self.gradient_evaluate = gradient_evaluate
68 self.step_size = step_size
69 super().__init__(container, budget, x0, sigma0, batch_size, threshold_min, **kwargs)
70
71 def reinit(self):
72 """Reset the centre, coefficient strategy, and gradient evaluation count."""
73 super().reinit()
74 self._centre = self.x0.copy()
76 self._basis = None
77 self._centre_phase = False
78
79 @property
80 def centre(self):
81 """Return a copy of the current gradient search point."""
82 return self._centre.copy()
83
84 @property
86 """Number of attempted centre evaluations, including failed calls."""
87 return self._gradient_evaluations
88
89 def _fixed_batch_plan(self, size, evaluate, packed):
90 if self._basis is None:
91 return 1, self.gradient_evaluate, False
92 return size, evaluate, packed
93
94
95 def ask_dqd(self):
96 """Return the centre, ready for a report through ``tell_dqd()``."""
97 if self._basis is not None:
98 raise RuntimeError("Complete an offspring batch before requesting another gradient.")
99 return super().ask_batch(1)[0]
100
101
102 def tell_dqd(self, result):
103 """Report a GradientEvaluation or ``None`` for a failed centre call."""
104 if not self._pending_size or not self._centre_phase:
105 raise RuntimeError("Use ask_dqd() before tell_dqd().")
106 super().tell_batch([result])
107
108 def ask_batch(self, size=None):
109 """Issue offspring after a successful centre evaluation."""
110 if self._basis is None:
111 raise RuntimeError("Use ask_dqd() and tell_dqd() before asking for offspring.")
112 return super().ask_batch(size)
113
114 def tell_batch(self, results):
115 """Commit the pending offspring in proposal order."""
116 if self._pending_size and self._centre_phase:
117 raise RuntimeError("Use tell_dqd() to report a centre evaluation.")
118 super().tell_batch(results)
119
120 def _sample_vectors(self, size):
121 self._centre_phase = self._basis is None
122 if self._centre_phase:
123 return [self._centre.copy()]
124 if self._strategy is None:
125 self._strategy = self._new_strategy(np.zeros(len(self._basis)), bounded=False)
126 self._coefficients = self._strategy.ask(number=size)
127 vectors = self._centre + np.asarray(self._coefficients) @ self._basis
128 return self._bounded(vectors)
129
130 def _bounded(self, vectors):
131 return vectors if self.ind_domain is None else np.clip(vectors, *self.ind_domain)
132
133 def _centre_payload(self, result):
134 if not isinstance(result, GradientEvaluation):
135 raise TypeError("The centre evaluator must return a GradientEvaluation.")
136 count = len(self.container.features_domain)
137 jacobian = np.asarray(result.jacobian, dtype=float)
138 descriptors = np.asarray(result.descriptors, dtype=float)
139 if jacobian.shape != (count + 1, self.dimension) or not np.all(np.isfinite(jacobian)):
140 raise ValueError("The centre Jacobian must be finite and match the objective and descriptors.")
141 if descriptors.shape != (count,) or not np.all(np.isfinite(descriptors)) or not isfinite(result.fitness):
142 raise ValueError("The centre fitness and descriptor vector must be finite and match the grid.")
143 self._basis = _gradient_basis(jacobian, self._fitness_weights[0])
144 return (result.fitness,), descriptors
145
146 def _receive_fixed_batch(self, records, verbose, batch_start_time):
147 if self._centre_phase:
148 candidate, result, elapsed = records[0]
149 self._gradient_evaluations += 1
150 if result is not None:
151 try:
152 result = self._centre_payload(result)
153 except (TypeError, ValueError, OverflowError) as error:
154 warnings.warn(f"Invalid gradient evaluation: {error}", stacklevel=2)
155 result = None
156 records = [(candidate, result, elapsed)]
157 super()._receive_fixed_batch(records, verbose, batch_start_time)
158
159 def _restart_arborescence(self):
160 self._strategy = None
161 self._centre = np.asarray(self._restart_center(), dtype=float).copy()
162
163 def _clear_generation(self):
164 super()._clear_generation()
165 self._coefficients = ()
166
167 def _commit_generation(self, evaluated):
168 admitted = self._update_annealed_archive(evaluated)
169 if self._centre_phase:
170 if evaluated[0] is None:
171 self._basis = None
173 return admitted
174
175 if len(evaluated) == self.batch_size and any(ind is not None for ind in evaluated):
176 order = self._adapt_strategy(self._coefficients)
177 selected = order[:self._strategy.sp.mu]
178 selected = selected[np.isfinite(self._gains[selected])]
179 if len(selected):
180 weights = np.asarray(self._strategy.sp.weights[:len(selected)])
181 moves = self._vectors[selected] - self._centre
182 self._centre = self._bounded(self._centre + self.step_size * np.average(moves, axis=0, weights=weights))
183 if self._strategy.stop() or not np.any(self._gains > 0):
185 self._basis = None
186 return admitted
187
188
189
191@registry.register
193 """Analytic CMA-MEGA, with Adam for the centre update by default.
194
195 Each branch generation uses one measured Jacobian at the centre.
196 New cells rank above same-cell improvements. Rejected offspring rank
197 below both. Offspring use the ordinary QDpy evaluator.
198
199 :param container: Empty best-only scalar Grid or CVTGrid without parents.
200 :param budget: Total candidate calls, including centre Jacobians.
201 :param x0: Starting point in genome coordinates.
202 :param sigma0: Initial standard deviation in coefficient space.
203 :param batch_size: Number of candidate branches per Jacobian.
204 :param gradient_evaluate: Callable returning a GradientEvaluation.
205 :param step_size: Learning rate for the centre update.
206 :param centre_optimizer: "adam" or the paper's plain "gradient" update.
207 :param kwargs: Native algorithm settings, including ind_domain and seed.
208 """
209
210 def __init__(self, container, budget, x0, sigma0, batch_size, *, gradient_evaluate,
211 step_size=.05, centre_optimizer="adam", **kwargs):
212 _validate_grid(container)
213 if container.parents:
214 raise ValueError("Use an empty parentless best-only archive for CMA-MEGA.")
215 if centre_optimizer not in ("adam", "gradient"):
216 raise ValueError("centre_optimizer must be 'adam' or 'gradient'.")
217 self.centre_optimizer = centre_optimizer
218 if container.fitness_weights is not None:
219 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
220 super().__init__(container, budget, x0, sigma0, batch_size, 0.,
221 gradient_evaluate=gradient_evaluate, step_size=step_size, **kwargs)
222
223 def _reset_moments(self):
224 self._first = np.zeros_like(self.x0)
225 self._second = np.zeros_like(self.x0)
226 self._adam_steps = 0
227
228 def reinit(self):
229 """Reset the coefficient distribution, centre, and Adam state."""
230 super().reinit()
231 self._reset_moments()
232
233 def _restart_arborescence(self):
234 self._strategy = None
235 self._centre = self._bounded(np.asarray(self._search_rng().choice(list(self.container))
236 if self.container else self.x0, dtype=float)).copy()
237 self._reset_moments()
238
239 def _move_centre(self, direction):
240 if self.centre_optimizer == "adam":
241 self._adam_steps += 1
242 self._first = .9 * self._first + .1 * direction
243 self._second = .999 * self._second + .001 * direction ** 2
244 first = self._first / (1. - .9 ** self._adam_steps)
245 second = self._second / (1. - .999 ** self._adam_steps)
246 direction = first / (np.sqrt(second) + 1e-8)
247 self._centre = self._bounded(self._centre + self.step_size * direction)
248
249 @property
250 def search_elites(self):
251 """Return the best measured candidate in each occupied cell."""
252 return {cell: front[0] for cell, front in self.container.solutions.items() if front}
253
254 def threshold(self, cell):
255 """Return signed incumbent fitness, or negative infinity for an empty cell."""
256 front = self.container.solutions[cell]
257 return np.sign(self._fitness_weights[0]) * self.container.get_ind_fitness(front[0]).values[0] if front else -np.inf
258
259 def _commit_generation(self, evaluated):
260 self._gains = np.full(len(evaluated), -np.inf)
261 statuses = np.zeros(len(evaluated), dtype=int)
262 admitted = set()
263 direction = np.sign(self._fitness_weights[0])
264 for index, candidate in enumerate(evaluated):
265 if candidate is None:
266 continue
267 cell = self.container.index_grid(candidate)
268 front = self.container.solutions[cell]
269 value = direction * self.container.get_ind_fitness(candidate).values[0]
270 new_cell = not front
271 self._gains[index] = value if new_cell else value - self.threshold(cell)
272 if self._offer_to_grid(candidate, cell):
273 statuses[index] = 2 if new_cell else 1
274 admitted.add(index)
275
276 if self._centre_phase:
277 if evaluated[0] is None:
278 self._basis = None
280 return admitted
281
282 if len(evaluated) == self.batch_size:
283 if admitted:
284 order = np.lexsort((-self._gains, -statuses))
285 losses = np.empty(len(order), dtype=int)
286 losses[order] = np.arange(len(order))
287 selected = order[:self._strategy.sp.mu]
288 selected = selected[np.isfinite(self._gains[selected])]
289 if len(selected):
290 weights = np.asarray(self._strategy.sp.weights[:len(selected)])
291 moves = self._vectors[selected] - self._centre
292 self._move_centre(np.average(moves, axis=0, weights=weights))
293 self._strategy.tell(self._coefficients, losses)
294 if not admitted or self._strategy.stop():
296 self._basis = None
297 return admitted
Adapt coefficients on a basis of objective and descriptor gradients.
_receive_fixed_batch(self, records, verbose, batch_start_time)
_fixed_batch_plan(self, size, evaluate, packed)
tell_dqd(self, result)
Report the gradient evaluation for the pending centre.
ask_dqd(self)
Issue the current centre for a gradient evaluation.
Adapt gradient coefficient samples by best-only archive improvement.
Raw objective, descriptors, and their derivatives at a search point.
Adapt a covariance matrix using annealed cell-level improvement.
Definition modern.py:343
_update_annealed_archive(self, evaluated)
Definition modern.py:411
_new_strategy(self, center, *, bounded=True)
Definition modern.py:308
_offer_to_grid(self, individual, cell)
Definition modern.py:228