QDpy
Loading...
Searching...
No Matches
descriptor_cma.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Continuous black-box QD search with optional pycma strategies."""
6
7from collections import deque
8from dataclasses import dataclass
9from functools import partial
10import numpy as np
11from scipy.spatial.distance import cdist
12from scipy.special import logsumexp
13from scipy.stats import rankdata
14
15from qdpy.containers import Grid
16from .differentiable import _gradient_basis
17from .modern import _cma_strategy, _positive_int
18from .task_search import _measure, _offer, _offer_with_age, _search_bounds, _validate_grid
19
20__all__ = ["DDSResult", "DynamicCMAResult", "CMAMEGAESResult", "dds_kde",
21 "dynamic_cma_me", "cma_mega_es"]
22
23
24
25@dataclass(frozen=True)
27 """Evaluator attempts, failed calls, and final descriptor reservoir size."""
28
29 archive: Grid
30 attempts: int
31 failures: int
32 reservoir_size: int
33
34
35
36@dataclass(frozen=True)
38 """Search, change detection and refresh counts, including failed attempts."""
39
40 archive: Grid
41 offspring_attempts: int
42 detection_attempts: int
43 refresh_attempts: int
44 failures: int
45 detected_change_ticks: tuple[int, ...]
46 incomplete_updates: int
47
48 @property
49 def attempts(self):
50 """Return the complete evaluation cost of this run."""
51 return self.offspring_attempts + self.detection_attempts + self.refresh_attempts
52
53
54
55@dataclass(frozen=True)
57 """Centre, perturbation, and offspring attempts, including failed calls."""
58
59 archive: Grid
60 centre_attempts: int
61 perturbation_attempts: int
62 offspring_attempts: int
63 failures: int
64
65 @property
66 def attempts(self):
67 """Return the complete evaluation cost of this run."""
68 return self.centre_attempts + self.perturbation_attempts + self.offspring_attempts
69
70
71def _settings(archive, evaluate, x0, sigma0, batch_size, budget, ind_domain, on_step):
72 """Validate the shared archive, budget and CMA search domain."""
73 try:
74 import cma # noqa: F401
75 except ImportError as error:
76 raise ImportError("This method needs the QDpy 'cma' extra.") from error
77 _validate_grid(archive)
78 if not callable(evaluate) or (on_step is not None and not callable(on_step)):
79 raise TypeError("Supply a callable evaluator and, optionally, a callable step hook.")
80 bounds = None if ind_domain is None else _search_bounds(ind_domain)
81 center = np.array(x0, dtype=float, copy=True)
82 if center.ndim != 1 or center.size < 2 or not np.isfinite(center).all():
83 raise ValueError("x0 must be a finite vector with at least two coordinates.")
84 if bounds is not None and not np.array_equal(center, np.clip(center, *bounds)):
85 raise ValueError("x0 lies outside the genome bounds.")
86 batch_size = _positive_int(batch_size, "batch_size")
87 if batch_size < 2 or not 0 < sigma0 < np.inf:
88 raise ValueError("Use a CMA batch of at least two and positive finite sigma0.")
89 return center, bounds, batch_size, _positive_int(budget, "budget")
90
91
92def _strategy(center, sigma, population, rng, bounds=None):
93 return _cma_strategy(center, sigma, population, int(rng.integers(1, 2**32)), bounds)
94
95
96def _worker(evaluate, genome):
97 try:
98 return evaluate(genome), None
99 except Exception as error:
100 return None, f"{type(error).__name__}: {error}"
101
102
103def _unwrap(result, error):
104 if error is not None:
105 raise ValueError(error)
106 return result
107
108
109def _measure_group(archive, evaluate, vectors, executor):
110 genomes = [tuple(map(float, vector)) for vector in vectors]
111 if executor is None:
112 return [_measure(archive, evaluate, (genome,), genome) for genome in genomes]
113 responses = executor.map(partial(_worker, evaluate), genomes)
114 return [_measure(archive, _unwrap, response, genome)
115 for genome, response in zip(genomes, responses, strict=True)]
116
117
118def _losses(order):
119 losses = np.empty(len(order), dtype=int)
120 losses[order] = np.arange(len(order))
121 return losses
122
123
124def _improvements(archive, measurements, *, ages=None, tick=None):
125 """Rank new cells first, then improvements, then rejected candidates."""
126 scores = []
127 accepted = 0
128 offer = _offer if ages is None else partial(_offer_with_age, last_touched=ages, step=tick)
129 for measurement in measurements:
130 if measurement is None or measurement[1] is None:
131 scores.append((-1, 0.0))
132 continue
133 candidate, cell = measurement
134 front = archive.solutions[cell]
135 quality = archive.get_ind_fitness(candidate)
136 direction = 1 if quality.weights[0] > 0 else -1
137 value = quality.values[0]
138 prior = archive.get_ind_fitness(front[0]).values[0] if front else 0.0
139 improvement = direction * (value - prior)
140 status = 1 if front else 2
141 before = archive.nb_added
142 offer(archive, measurement)
143 if archive.nb_added == before:
144 status = 0
145 else:
146 accepted += 1
147 scores.append((status, improvement))
148 return sorted(range(len(scores)), key=scores.__getitem__, reverse=True), accepted
149
150
151def _restart_center(archive, fallback, rng):
152 return np.asarray(archive[rng.integers(len(archive))]) if archive else fallback
153
154
155def _negative_log_density(points, previous, bandwidth):
156 """Rank Gaussian KDEs in log space so remote points retain separation."""
157 if not len(previous):
158 return np.zeros(len(points))
159 result = np.empty(len(points))
160 for start in range(0, len(points), 64):
161 stop = start + 64
162 squared = cdist(points[start:stop], previous, metric="sqeuclidean")
163 with np.errstate(over="ignore"):
164 scaled = (squared / bandwidth) / bandwidth
165 result[start:stop] = -logsumexp(-0.5 * scaled, axis=1)
166 return result
167
168
169
170def dds_kde(archive, evaluate, *, x0, budget, bandwidth, reservoir_size=1024,
171 sigma0=0.15, batch_size=16, ind_domain=(0, 1), seed=0, executor=None,
172 on_step=None):
173 """Run Density Descent Search with kernel density estimation.
174
175 Each generation is ranked against the descriptor reservoir from earlier
176 generations. Reuse the previous order to break equal densities. Offer
177 measured solutions to a passive archive. Fitness and archive admission
178 never enter CMA feedback. Valid measurements outside the archive's
179 bounds still inform the density model.
180
181 :param archive: Empty, parentless, best-only Grid or CVTGrid.
182 :param evaluate: Callable taking an immutable genome and returning
183 a singleton fitness vector and its descriptors. Use constant fitness
184 for a pure diversity task.
185 :param x0: Initial genome for CMA and its restarts.
186 :param budget: Total attempted evaluations.
187 :param bandwidth: Positive Gaussian bandwidth in descriptor units.
188 :param reservoir_size: Maximum number of past descriptors to retain.
189 :param sigma0: Initial CMA sampling scale in genome coordinates.
190 :param batch_size: CMA population size. Commit a final partial batch
191 to the passive archive and reservoir.
192 :param ind_domain: Shared bounds, or None for unbounded search.
193 :param seed: Private seed for CMA and uniform reservoir sampling.
194 :param executor: Optional caller-owned executor with ordered map.
195 :param on_step: Optional callback receiving the archive, iteration and evaluations.
196 :returns: Passive archive and run accounting.
197 """
198 if not 0 < bandwidth < np.inf:
199 raise ValueError("KDE bandwidth must be finite and positive.")
200 return _density_descent(archive, evaluate, x0, budget, reservoir_size, sigma0, batch_size,
201 ind_domain, seed, executor, on_step,
202 lambda points, previous, _: _negative_log_density(points, previous, bandwidth))
203
204
205def _density_descent(archive, evaluate, x0, budget, reservoir_size, sigma0, batch_size,
206 ind_domain, seed, executor, on_step, negative_log_density):
207 """Rank valid candidates against an estimator using the previous descriptor reservoir."""
208 center, bounds, batch_size, budget = _settings(
209 archive, evaluate, x0, sigma0, batch_size, budget, ind_domain, on_step)
210 reservoir_size = _positive_int(reservoir_size, "reservoir_size")
211 cma_seed, buffer_seed = np.random.SeedSequence(seed).spawn(2)
212 rng, buffer_rng = np.random.default_rng(cma_seed), np.random.default_rng(buffer_seed)
213 buffer = np.empty((min(reservoir_size, budget), len(archive.features_domain)))
214 seen = failures = 0
215 strategy = None
216 for iteration, start in enumerate(range(0, budget, batch_size), 1):
217 size = min(batch_size, budget - start)
218 if strategy is None or strategy.stop():
219 strategy = _strategy(center, sigma0, batch_size, rng, bounds)
220 vectors = strategy.ask(number=size)
221 measurements = _measure_group(archive, evaluate, vectors, executor)
222 valid = [slot for slot, measure in enumerate(measurements) if measure is not None]
223 failures += size - len(valid)
224 if valid:
225 descriptors = np.asarray([tuple(measurements[slot][0].features) for slot in valid])
226 density_ranks = np.argsort(
227 -negative_log_density(descriptors, buffer[:min(seen, reservoir_size)], iteration), kind="stable")
228 if size == batch_size:
229 # Failures follow even a valid candidate with negligible density.
230 order = [valid[item] for item in density_ranks]
231 order.extend(slot for slot, measure in enumerate(measurements) if measure is None)
232 strategy.tell(vectors, _losses(order))
233 for slot, descriptor in zip(valid, descriptors):
234 _offer(archive, measurements[slot])
235 seen += 1
236 target = seen - 1 if seen <= reservoir_size else buffer_rng.integers(seen)
237 if target < reservoir_size:
238 buffer[target] = descriptor
239 elif size == batch_size:
240 strategy = None
241 if on_step is not None:
242 on_step(archive, iteration=iteration, evaluations=start + size)
243 return DDSResult(archive, budget, failures, min(seen, reservoir_size))
244
245
246def _refresh_replacees(archive, offspring, probe, probe_measurement, remeasure):
247 """Stage one probe and all incumbent moves against the unchanged archive."""
248 pending = deque([probe])
249 for measurement in offspring:
250 if measurement is not None and measurement[1] is not None:
251 pending.extend(archive.solutions[measurement[1]])
252 refreshed = {}
253 while pending:
254 incumbent = pending.popleft()
255 key = id(incumbent)
256 if key in refreshed:
257 continue
258 fresh = probe_measurement if incumbent is probe else remeasure(incumbent)
259 if fresh is None:
260 return None
261 refreshed[key] = fresh
262 if fresh[1] is not None:
263 pending.extend(archive.solutions[fresh[1]])
264 return refreshed
265
266
267
268def dynamic_cma_me(archive, evaluate, *, x0, budget, sigma0=0.15,
269 batch_size=16, ind_domain=(0, 1), seed=0, refresh=True, on_step=None):
270 """Run Dynamic CMA-ME with oldest-elite detection and replacee refresh.
271
272 A generation shares one tick, the number of attempts already spent
273 when it starts. Probe the least recently checked elite, including with
274 the final available call. If the probe changed, refresh occupied
275 destinations and follow incumbent moves. Commit the updates together
276 before ranking offspring by cell improvement. Failed or unfinished
277 refreshes leave the archive untouched and restart the strategy.
278 Only offspring from a full generation enter CMA feedback.
279
280 :param archive: Empty, parentless, best-only Grid or CVTGrid.
281 :param evaluate: Callable taking an immutable genome and a tick.
282 Return a singleton fitness vector and its descriptors.
283 :param x0: Initial genome used before the first archive admission.
284 :param budget: All attempted evaluations, including probes and refreshes.
285 :param sigma0: Initial CMA sampling scale.
286 :param batch_size: CMA population size.
287 :param ind_domain: Common bounds, or None for unbounded search.
288 :param seed: Private CMA and restart seed.
289 :param refresh: Enable detection and refresh. False runs static CMA-ME
290 with the same improvement emitter and tick convention.
291 :param on_step: Optional callback receiving the archive, iteration and evaluations.
292 :returns: The live archive and counts per evaluation phase.
293 """
294 center, bounds, batch_size, budget = _settings(
295 archive, evaluate, x0, sigma0, batch_size, budget, ind_domain, on_step)
296 if type(refresh) is not bool:
297 raise ValueError("refresh must be a bool.")
298 rng = np.random.default_rng(seed)
299 strategy = None
300 last_checked = {}
301 offspring_count = probes = refresh_count = failures = incomplete = iteration = 0
302 detected = []
303
304 def used():
305 return offspring_count + probes + refresh_count
306
307 while used() < budget:
308 iteration += 1
309 tick = used()
310 probe = fresh_probe = None
311 changed = False
312 if refresh and archive:
313 probe = min(archive, key=lambda elite: last_checked[id(elite)])
314 genome = tuple(probe)
315 probes += 1
316 fresh_probe = _measure(archive, evaluate, (genome, tick), genome)
317 failures += fresh_probe is None
318 if fresh_probe is not None:
319 candidate = fresh_probe[0]
320 changed = (candidate.fitness.values != probe.fitness.values
321 or tuple(candidate.features) != tuple(probe.features))
322 if changed:
323 detected.append(tick)
324
325 size = min(batch_size, budget - used())
326 vectors = []
327 if size:
328 if strategy is None or strategy.stop():
329 strategy = _strategy(_restart_center(archive, center, rng), sigma0, batch_size, rng, bounds)
330 vectors = strategy.ask(number=size)
331 offspring = []
332 for vector in vectors:
333 genome = tuple(map(float, vector))
334 offspring_count += 1
335 measurement = _measure(archive, evaluate, (genome, tick), genome)
336 offspring.append(measurement)
337 failures += measurement is None
338
339 def new_measurement(elite):
340 nonlocal refresh_count, failures
341 if used() >= budget:
342 return None
343 genome = tuple(elite)
344 refresh_count += 1
345 result = _measure(archive, evaluate, (genome, tick), genome)
346 failures += result is None
347 return result
348
349 staged = _refresh_replacees(archive, offspring, probe, fresh_probe, new_measurement) if changed else {}
350 if staged is None or (probe is not None and fresh_probe is None):
351 incomplete += 1
352 strategy = None
353 else:
354 old = [elite for elite in archive if id(elite) in staged]
355 if probe is not None and not changed:
356 last_checked[id(probe)] = tick
357 for elite in old:
358 archive.discard(elite)
359 del last_checked[id(elite)]
360 for elite in old:
361 _offer_with_age(archive, staged[id(elite)], last_checked, tick)
362 order, admitted = _improvements(archive, offspring, ages=last_checked, tick=tick)
363 if size == batch_size:
364 if admitted:
365 strategy.tell(vectors, _losses(order))
366 else:
367 strategy = None
368 if on_step is not None:
369 on_step(archive, iteration=iteration, evaluations=used())
370 last_checked = {id(elite): last_checked.get(id(elite), tick) for elite in archive}
371 return DynamicCMAResult(archive, offspring_count, probes, refresh_count, failures, tuple(detected), incomplete)
372
373
374def _rank_gradients(noise, positive, negative):
375 """Form mirrored ES gradients using combined per-output ranks."""
376 ranks = rankdata(np.concatenate((positive, negative)), method="average", axis=0)
377 first, second = np.split(ranks, 2, axis=0)
378 # The positive common ES scale cancels when each gradient is normalised.
379 return (first - second).T @ noise
380
381
382def _es_basis(noise, measurements, objective_weight):
383 """Estimate rank gradients from complete mirrored pairs and normalise each row."""
384 pairs = len(noise)
385 complete = [slot for slot in range(pairs)
386 if measurements[slot] is not None and measurements[slot + pairs] is not None]
387 if not complete:
388 return None
389 values = []
390 for slot in [*complete, *(slot + pairs for slot in complete)]:
391 candidate = measurements[slot][0]
392 values.append((*candidate.fitness.values, *candidate.features))
393 split = len(complete)
394 return _gradient_basis(_rank_gradients(noise[complete], values[:split], values[split:]), objective_weight)
395
396
397
398def cma_mega_es(archive, evaluate, *, x0, budget, es_samples=32, es_sigma=0.02,
399 sigma0=0.2, step_size=1.0, batch_size=16, ind_domain=(0, 1),
400 seed=0, executor=None, on_step=None):
401 """Run CMA-MEGA (ES) with measured fitness and black-box descriptors.
402
403 Evaluate the centre and mirrored perturbations first. Use one rank
404 gradient per output, estimated from the same perturbations. Offer
405 all valid measurements to the archive. Branch along combinations of
406 the normalised gradients and adapt CMA in coefficient space using
407 archive improvement. Advance the centre by rank-weighted gradient
408 ascent. If the budget ends, archive measured partial phases without
409 adapting CMA from a short batch. Discard incomplete mirrored pairs
410 when estimating gradients.
411
412 :param archive: Empty, parentless, best-only Grid or CVTGrid.
413 :param evaluate: Callable taking an immutable real-valued genome and
414 returning a singleton fitness vector and its descriptors.
415 :param x0: Initial centre in genome coordinates.
416 :param budget: Total attempted centre, perturbation and offspring evaluations.
417 :param es_samples: Even number of perturbations including both signs.
418 :param es_sigma: Perturbation standard deviation in genome coordinates.
419 :param sigma0: Initial CMA step size in gradient coefficient coordinates.
420 :param step_size: Multiplier for the rank-weighted centre displacement.
421 :param batch_size: CMA offspring population size.
422 :param ind_domain: Inclusive bounds, or None for unbounded search.
423 :param seed: Private seed for perturbations, CMA and restart centres.
424 :param executor: Optional caller-owned executor with ordered map.
425 :param on_step: Optional callback receiving the archive, iteration and evaluations.
426 :returns: The live archive and counts for each phase.
427 """
428 initial, bounds, batch_size, budget = _settings(
429 archive, evaluate, x0, sigma0, batch_size, budget, ind_domain, on_step)
430 es_samples = _positive_int(es_samples, "es_samples")
431 if es_samples % 2 or es_samples < 2:
432 raise ValueError("es_samples must be even and at least two.")
433 if not 0 < es_sigma < np.inf or not 0 < step_size < np.inf:
434 raise ValueError("ES noise and centre step must be finite and positive.")
435 rng = np.random.default_rng(seed)
436 dimension = len(initial)
437 basis_size = len(archive.features_domain) + 1
438 weight = -1.0 if archive.fitness_weights is None else archive.fitness_weights[0]
439 center = initial
440 strategy = None
441 centre_count = perturbations = offspring_count = failures = iteration = 0
442
443 def used():
444 return centre_count + perturbations + offspring_count
445
446 def bounded(vectors):
447 return vectors if bounds is None else np.clip(vectors, *bounds)
448
449 while used() < budget:
450 iteration += 1
451 count = min(es_samples, budget - used() - 1)
452 noise = rng.standard_normal((min(count, es_samples // 2), dimension))
453 shifts = np.concatenate((noise, -noise[:count - len(noise)]))
454 points = bounded(np.vstack((center, center + es_sigma * shifts)))
455 measurements = _measure_group(archive, evaluate, points, executor)
456 centre_count += 1
457 perturbations += count
458 failures += sum(result is None for result in measurements)
459 for result in measurements:
460 if result is not None:
461 _offer(archive, result)
462 basis = _es_basis(noise, measurements[1:], weight) if count == es_samples else None
463
464 if used() < budget:
465 if basis is None or not np.any(basis):
466 center = _restart_center(archive, initial, rng)
467 strategy = None
468 else:
469 if strategy is None:
470 strategy = _strategy(np.zeros(basis_size), sigma0, batch_size, rng)
471 size = min(batch_size, budget - used())
472 coefficients = strategy.ask(number=size)
473 vectors = bounded(center + np.asarray(coefficients) @ basis)
474 offspring = _measure_group(archive, evaluate, vectors, executor)
475 offspring_count += size
476 failures += sum(result is None for result in offspring)
477 order, admitted = _improvements(archive, offspring)
478 if size == batch_size:
479 if admitted:
480 strategy.tell(coefficients, _losses(order))
481 ranked = [slot for slot in order if offspring[slot] is not None and offspring[slot][1] is not None]
482 selected = ranked[:strategy.sp.mu]
483 weights = np.asarray(strategy.sp.weights[:len(selected)])
484 center = bounded(center + step_size * np.average(
485 vectors[selected] - center, axis=0, weights=weights))
486 if not admitted or strategy.stop():
487 center = _restart_center(archive, initial, rng)
488 strategy = None
489 if on_step is not None:
490 on_step(archive, iteration=iteration, evaluations=used())
491 return CMAMEGAESResult(archive, centre_count, perturbations, offspring_count, failures)
Live archive and counts for each arborescence evaluation phase.
Live passive archive and density search accounting.
Dynamic archive and separately accounted evaluation phases.