QDpy
Loading...
Searching...
No Matches
ga_me.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Gradient-Augmented MAP-Elites over a differentiable frozen surrogate."""
7
8from dataclasses import dataclass
9from operator import index
10
11import numpy as np
12from scipy.linalg import cho_solve
13from scipy.stats import qmc
14
15from qdpy.phenotype import Features, Fitness, Individual
16from qdpy.tools import iso_line_dd
17
18from .modern import _positive_int
19from .offline import OfflineMAPElites, OfflineSearchResult, _empty_geometry, _insert
20
21__all__ = ["GradientAugmentedMAPElites", "GAMESearchResult"]
22
23
24
25@dataclass(frozen=True)
27 """Keep the best predicted elites across all cycles and dropout events."""
28
29 targeting_predictions: int
30 refinement_predictions: int
31 dropped_elites: int
32
33
34def _matern_jacobian(point, centers, coefficients, length):
35 """Differentiate the Matérn-5/2 mean at a normalized decision vector."""
36 # Use unit directions before the derivative to limit intermediate scaling.
37 with np.errstate(over="ignore"):
38 offsets = (point - centers) / length
39 radius = np.sqrt(5.) * np.linalg.norm(offsets, axis=1)
40 active = (radius > 0.) & (radius <= 700.)
41 derivative = np.zeros_like(centers)
42 distance = radius[active]
43 with np.errstate(over="ignore"):
44 scale = -(5. / 3.) * ((1. + distance) * np.exp(-distance)) / length
45 derivative[active] = scale[:, None] * offsets[active]
46 return derivative.T @ coefficients
47
48
49
51 """Build a surrogate prediction map following Kent's GA-ME.
52
53 Target Sobol descriptor points from nearby logged designs. Alternate
54 variation with local ascent on newly improved elites. Accept refinement
55 moves that improve predicted fitness within the original cell.
56 Drop random breeders between cycles and retain a separate result
57 archive. Search charges every surrogate query, including gradients
58 and rejected moves. Inherited verify() measures selected designs
59 independently.
60
61 :param archive: Empty best-only Grid or CVTGrid with finite descriptor bounds.
62 :param genomes: Matrix of real-valued logged genomes.
63 :param fitnesses: One scalar outcome per logged genome.
64 :param descriptors: One measured descriptor vector per logged genome.
65 :param kwargs: OfflineMAPElites genome, kernel, mutation, and seed settings.
66 GA-ME searches posterior means. Use the default uncertainty_weight=0.
67 """
68
69 def __init__(self, archive, genomes, fitnesses, descriptors, **kwargs):
70 if kwargs.get("uncertainty_weight", 0.) != 0.:
71 raise ValueError("GA-ME refines posterior means. Set uncertainty_weight=0.")
72 super().__init__(archive, genomes, fitnesses, descriptors, **kwargs)
73 bounds = np.asarray(archive.features_domain, dtype=float)
74 with np.errstate(over="ignore"):
75 spans = bounds[:, 1] - bounds[:, 0]
76 if not np.all(np.isfinite(spans) & (spans > 0.)):
77 raise ValueError("GA-ME needs finite positive descriptor spans.")
78 self._feature_low, self._feature_span = bounds[:, 0].copy(), spans
79 self._logged_features = (np.asarray(descriptors, dtype=float) - self._feature_low) / spans
80 outputs = np.column_stack((fitnesses, descriptors))
81 # Public L_ already factorizes the fixed kernel. Solving in raw
82 # units recovers coefficients without scikit-learn's private scales.
83 self._coefficients = cho_solve((self._model.L_, True), outputs - outputs.mean(axis=0))
84
85 def _prediction(self, point, gradient):
86 normalized = self._normalized(np.asarray(point))
87 means, deviations = self._model.predict(normalized[None], return_std=True)
88 mean, *features = means[0]
89 deviation = deviations[0, 0]
90 if not np.isfinite((mean, deviation, *features)).all():
91 raise ValueError("The frozen surrogate produced a nonfinite prediction.")
92 candidate = Individual(list(point), fitness=Fitness((mean,), weights=self._source.fitness_weights),
93 features=Features(features),
94 scores={"predicted_fitness": float(mean), "prediction_std": float(deviation)})
95 jacobian = None
96 if gradient:
97 jacobian = _matern_jacobian(normalized, self._model.X_train_, self._coefficients,
98 self._model.kernel_.length_scale)
99 if not np.isfinite(jacobian).all():
100 raise ValueError("The frozen surrogate produced a nonfinite gradient.")
101 return candidate, jacobian
102
103 def _move(self, point, direction, rate):
104 scale = np.max(np.abs(direction))
105 if not scale:
106 return None
107 unit = direction / scale
108 normalized = self._normalized(np.asarray(point))
109 moved = self.ind_domain[0] + self._width * np.clip(normalized + rate * unit / np.linalg.norm(unit), 0., 1.)
110 moved = np.clip(moved, *self.ind_domain)
111 return None if np.array_equal(moved, point) else moved
112
113
115 def run(self, budget, *, initial_samples=16, targeting_steps=3, mutation_steps=24, refinement_steps=3,
116 dropout=.25, step_size=.08):
117 """Return an independently reproducible prediction map.
118
119 Target at most initial_samples descriptor points, each using
120 up to targeting_steps gradient moves. Each cycle uses mutation_steps
121 evaluated candidates, then up to refinement_steps moves for each
122 new elite. Set either gradient phase to zero for ablation.
123 """
124 budget = _positive_int(budget, "budget")
125 initial = _positive_int(initial_samples, "initial_samples")
126 mutation = _positive_int(mutation_steps, "mutation_steps")
127 targeting, refinement = index(targeting_steps), index(refinement_steps)
128 if min(targeting, refinement) < 0 or not (0 <= dropout <= 1 and 0 < step_size < np.inf):
129 raise ValueError("Use nonnegative gradient steps, dropout in [0, 1], and a positive finite step size.")
130 active, report = _empty_geometry(self._source), _empty_geometry(self._source)
131 geometry, rng = map(np.random.default_rng, np.random.SeedSequence(self.seed).spawn(2))
132 sobol = qmc.Sobol(len(self._feature_span), scramble=True, seed=int(geometry.integers(2**32)))
133 seed_order = rng.permutation(len(self._genomes))
134 used = target_cost = refine_cost = drops = 0
135
136 def measure(point, gradient=False):
137 nonlocal used
138 used += 1
139 return self._prediction(point, gradient)
140
141 def offer(candidate):
142 _insert(report, candidate)
143 before = active.nb_added
144 cell = _insert(active, candidate)
145 return cell if before != active.nb_added else None
146
147 for slot in range(min(initial, budget)):
148 target = sobol.random(1)[0]
149 if targeting:
150 offsets = self._logged_features - target
151 first = np.argmin(np.linalg.norm(offsets, axis=1))
152 else:
153 first = seed_order[slot % len(seed_order)]
154 point = self._genomes[first]
155 start = used
156 for step in range(targeting + 1):
157 if used == budget:
158 break
159 candidate, jacobian = measure(point, step < targeting)
160 offer(candidate)
161 if jacobian is None:
162 break
163 distance = (np.asarray(candidate.features.values) - self._feature_low) / self._feature_span - target
164 point = self._move(point, -(jacobian[:, 1:] / self._feature_span) @ distance, step_size)
165 if point is None:
166 break
167 target_cost += used - start
168 if used == budget:
169 break
170
171 while used < budget:
172 changed = {}
173 for _ in range(min(mutation, budget - used)):
174 if active:
175 first, second = rng.integers(len(active), size=2)
176 point = iso_line_dd(active[first], active[second], bounds=self.ind_domain,
177 iso_sigma=self._iso_sigma, line_sigma=self._line_sigma, rng=rng)
178 else:
179 point = rng.uniform(*self.ind_domain, size=self._genomes.shape[1])
180 candidate, _ = measure(point)
181 cell = offer(candidate)
182 if cell is not None:
183 changed[cell] = candidate
184 for cell, incumbent in changed.items():
185 rate = step_size
186 for _ in range(refinement):
187 if budget - used < 2:
188 break
189 _, jacobian = measure(incumbent, True)
190 refine_cost += 1
191 point = self._move(incumbent, self._direction * jacobian[:, 0], rate)
192 if point is None:
193 break
194 candidate, _ = measure(point)
195 refine_cost += 1
196 features = candidate.features.values
197 if (active.in_bounds(features, active.features_domain) and active.index_grid(features) == cell
198 and candidate.fitness.dominates(incumbent.fitness)):
199 if offer(candidate) is not None:
200 incumbent = candidate
201 continue
202 rate *= .5
203 if used < budget and dropout and active:
204 # Draw independently for each retained breeding elite.
205 for candidate in list(active):
206 if rng.random() < dropout:
207 active.discard(candidate)
208 drops += 1
209 return GAMESearchResult(report, used, target_cost, refine_cost, drops)
Report prediction calls per search phase and drops from the breeding archive.
Definition ga_me.py:26
Refine frozen-model elites while preserving a separate best-seen archive.
Definition ga_me.py:50
_move(self, point, direction, rate)
Definition ga_me.py:103
run(self, budget, *, initial_samples=16, targeting_steps=3, mutation_steps=24, refinement_steps=3, dropout=.25, step_size=.08)
Spend one shared surrogate budget on targeting, variation, and refinement.
Definition ga_me.py:116
Generate a predicted repertoire from a fixed dataset.
Definition offline.py:69
Predicted elites and number of proposals assessed by the frozen model.
Definition offline.py:26
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405