QDpy
Loading...
Searching...
No Matches
dsage.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""DSAGE with batched prediction, ancillary observations, and stratified promotion."""
6
7from dataclasses import dataclass
8from math import ceil, isfinite, sqrt
9from operator import index
10
11import numpy as np
12
13from qdpy.containers import Grid
14from qdpy.phenotype import Features, Fitness, Individual
15
16from .modern import IsoLineMAPElites, _bounds, _positive_int
17
18__all__ = ["DSAGE", "DSAGEMeasurement", "DSAGESurrogate", "DSAGEStats"]
19
20
21
22@dataclass(frozen=True)
24 """Supply scalar fitness, descriptor coordinates, and optional ancillary targets."""
25
26 fitness: float
27 features: tuple[float, ...]
28 auxiliary: object = None
29
30
31
32@dataclass(frozen=True)
34 """Cumulative search costs."""
35
36 evaluations: int
37 surrogate_evaluations: int
38 model_fits: int
39
40
41
43 """Train a PyTorch MLP on encoded genome rows.
44
45 With ancillary targets, a first network predicts them. A second
46 network consumes the encoded genome and those predictions to
47 predict fitness and descriptors. Both losses train the first network.
48 When auxiliary targets are absent, train only the second network.
49 """
50
51 def __init__(self, *, width=64, epochs=30, learning_rate=.003, auxiliary_weight=1., seed=0):
52 self.width = _positive_int(width, "width")
53 self.epochs = _positive_int(epochs, "epochs")
54 if not (0 < learning_rate < np.inf and 0 <= auxiliary_weight < np.inf):
55 raise ValueError("Use a finite positive learning rate and nonnegative auxiliary weight.")
56 self.learning_rate, self.auxiliary_weight = learning_rate, auxiliary_weight
57 self._seed = int(np.random.default_rng(seed).integers(2**32))
58 self._model = None
59
60
61 def fit(self, x, targets, auxiliary=None):
62 """Fit using input rows and targets ordered as fitness then descriptors."""
63 try:
64 import torch
65 from torch import nn
66 except ImportError as error:
67 raise ImportError("The built-in DSAGE surrogate requires PyTorch.") from error
68
69 def normalized(values):
70 array = np.asarray(values, dtype=np.float32)
71 if array.ndim != 2 or not array.size or not np.isfinite(array).all():
72 raise ValueError("Surrogate training arrays must be finite two-dimensional matrices.")
73 tensor = torch.from_numpy(array)
74 mean, scale = tensor.mean(dim=0), tensor.std(dim=0, unbiased=False).clamp(min=1e-6)
75 if not torch.isfinite(mean).all() or not torch.isfinite(scale).all():
76 raise ValueError("Surrogate training normalisation overflowed.")
77 return (tensor - mean) / scale, mean, scale
78
79 x, xm, xs = normalized(x)
80 y, ym, ys = normalized(targets)
81 aux = normalized(auxiliary)[0] if auxiliary is not None else None
82 if len(x) != len(y) or (aux is not None and len(x) != len(aux)):
83 raise ValueError("Measurements and ancillary targets must match the input rows.")
84 n_aux = 0 if aux is None else aux.shape[1]
85
86 def network(inputs, outputs):
87 return nn.Sequential(nn.Linear(inputs, self.width, device="cpu"), nn.SiLU(),
88 nn.Linear(self.width, outputs, device="cpu"))
89
90 with torch.random.fork_rng(devices=[]):
91 torch.random.default_generator.manual_seed(self._seed)
92 ancillary = network(x.shape[1], n_aux) if n_aux else None
93 model = network(x.shape[1] + n_aux, y.shape[1])
94 parameters = list(model.parameters())
95 if ancillary is not None:
96 parameters.extend(ancillary.parameters())
97 optimizer = torch.optim.Adam(parameters, lr=self.learning_rate)
98 for _ in range(self.epochs):
99 if ancillary is None:
100 prediction = model(x)
101 loss = (prediction - y).square().mean()
102 else:
103 predicted_aux = ancillary(x)
104 prediction = model(torch.cat((x, predicted_aux), dim=1))
105 loss = (prediction - y).square().mean()
106 loss = loss + self.auxiliary_weight * (predicted_aux - aux).square().mean()
107 if not torch.isfinite(loss):
108 raise ValueError("Training the DSAGE surrogate produced a nonfinite loss.")
109 optimizer.zero_grad(set_to_none=True)
110 loss.backward()
111 optimizer.step()
112 self._model = model, ancillary, xm, xs, ym, ys
113
114
115 def predict(self, x):
116 """Return a matrix in the original target units."""
117 if self._model is None:
118 raise RuntimeError("Fit the surrogate before predicting.")
119 import torch
120
121 model, ancillary, xm, xs, ym, ys = self._model
122 x = torch.as_tensor(np.asarray(x, dtype=np.float32), device="cpu")
123 if x.ndim != 2 or x.shape[1] != len(xm) or not torch.isfinite(x).all():
124 raise ValueError("Prediction rows must match the fitted input width and be finite.")
125 with torch.no_grad():
126 inputs = (x - xm) / xs
127 if ancillary is not None:
128 inputs = torch.cat((inputs, ancillary(inputs)), dim=1)
129 return (model(inputs) * ys + ym).numpy()
130
131
132
133class DSAGE:
134 """Deep Surrogate Assisted Generation of Environments on fixed grids.
135
136 A bounded real genome can parameterize any caller-provided simulator.
137 The optional encoder builds a fixed-width vector for the surrogate.
138 For custom models, supply fit(X, targets, auxiliary) and predict(X),
139 with target columns ordered as fitness followed by descriptors.
140
141 Admit measured results to archive. The inner search illuminates a
142 separate predicted grid. Before simulation, uniformly pick an elite
143 from each selected occupied region of a coarser descriptor grid.
144 """
145
146 def __init__(self, archive, dimension, *, ind_domain=(0., 1.), initial_samples=24,
147 surrogate_evaluations=256, simulation_batch_size=8, prediction_batch_size=32,
148 downsample_shape=None, encoder=None, surrogate=None, seed=0, maximise=True):
149 if (type(archive) is not Grid or archive.max_items_per_bin != 1
150 or len(archive.fitness_domain) != 1 or archive.parents or len(archive)):
151 raise ValueError("DSAGE needs an empty parentless scalar Grid with one elite per cell.")
152 self.archive = archive
153 self.dimension = _positive_int(dimension, "dimension")
154 self.bounds = _bounds(ind_domain)
155 self.initial_samples = _positive_int(initial_samples, "initial_samples")
156 self.surrogate_budget = _positive_int(surrogate_evaluations, "surrogate_evaluations")
157 self.simulation_batch_size = _positive_int(simulation_batch_size, "simulation_batch_size")
158 self.prediction_batch_size = _positive_int(prediction_batch_size, "prediction_batch_size")
159 if downsample_shape is None:
160 downsample_shape = tuple(ceil(sqrt(n)) for n in archive.shape)
161 self._strata = tuple(_positive_int(n, "strata extent") for n in downsample_shape)
162 if len(self._strata) != len(archive.shape) or any(a > b for a, b in zip(self._strata, archive.shape)):
163 raise ValueError("Downsample strata must fit inside the archive shape.")
164 if encoder is not None and not callable(encoder):
165 raise TypeError("encoder must be callable.")
166 self._encoder = encoder
167 self.surrogate = DSAGESurrogate(seed=seed) if surrogate is None else surrogate
168 if not all(callable(getattr(self.surrogate, name, None)) for name in ("fit", "predict")):
169 raise TypeError("surrogate needs fit and predict methods.")
170 self._weights = (1.,) if maximise else (-1.,)
171 archive._set_fitness_weights(self._weights)
172 self._rng = np.random.default_rng(seed)
173 self._inputs, self._targets, self._auxiliary = [], [], []
174 self._trials = self._predictions = self._model_fits = 0
175 self.last_surrogate_archive = None
176
177 @property
178 def stats(self):
179 """Return the actual cumulative search costs."""
180 return DSAGEStats(self._trials, self._predictions, self._model_fits)
181
182 def _random(self):
183 return tuple(map(float, self._rng.uniform(*self.bounds, size=self.dimension)))
184
185 def _encode(self, genome):
186 features = np.asarray(genome if self._encoder is None else self._encoder(genome), dtype=float).ravel()
187 if not features.size or not np.isfinite(features).all():
188 raise ValueError("The encoded genome must be nonempty and finite.")
189 if self._inputs and len(features) != len(self._inputs[0]):
190 raise ValueError("The encoder must return a fixed number of values.")
191 return features.copy()
192
193 def _measure(self, genome, evaluate):
194 inputs = self._encode(genome)
195 self._trials += 1
196 result = evaluate(genome)
197 if not isinstance(result, DSAGEMeasurement):
198 raise TypeError("evaluate must return DSAGEMeasurement.")
199 value, features = float(result.fitness), tuple(map(float, result.features))
200 if not isfinite(value) or len(features) != len(self.archive.shape) or not all(map(isfinite, features)):
201 raise ValueError("Measured fitness and descriptors must be finite and match the grid.")
202 aux = None if result.auxiliary is None else np.asarray(result.auxiliary, dtype=float).ravel().copy()
203 if aux is not None and (not aux.size or not np.isfinite(aux).all()):
204 raise ValueError("Auxiliary observations must be nonempty and finite.")
205 if self._auxiliary and ((aux is None) != (self._auxiliary[0] is None)
206 or (aux is not None and aux.shape != self._auxiliary[0].shape)):
207 raise ValueError("All measurements must use the same auxiliary schema.")
208 individual = Individual(genome, fitness=Fitness((value,), weights=self._weights), features=Features(features))
209 if (self.archive.in_bounds((value,), self.archive.fitness_domain)
210 and self.archive.in_bounds(features, self.archive.features_domain)):
211 cell = self.archive.index_grid(features)
212 if self.archive.free or self.archive.solutions[cell]:
213 self.archive.add(individual)
214 self._inputs.append(inputs)
215 self._targets.append((value, *features))
216 self._auxiliary.append(aux)
217
218 def _promote(self, predicted, limit):
219 strata = {}
220 for item in predicted:
221 cell = predicted.index_grid(item)
222 region = tuple(i * k // n for i, k, n in zip(cell, self._strata, predicted.shape))
223 strata.setdefault(region, []).append(item)
224 groups = tuple(strata.values())
225 return [tuple(groups[i][int(self._rng.integers(len(groups[i])))])
226 for i in self._rng.permutation(len(groups))[:limit]]
227
228 def _illuminate(self):
229 from qdpy.simple import _coordinator_seed
230
231 archive = self.archive
232 imagined = Grid(shape=archive.shape, features_domain=archive.features_domain,
233 fitness_domain=archive.fitness_domain)
234 search = IsoLineMAPElites(imagined, budget=self.surrogate_budget, dimension=self.dimension,
235 ind_domain=self.bounds, optimisation_task=self._weights)
236 low, high = np.asarray((*archive.fitness_domain, *archive.features_domain)).T
237 with _coordinator_seed(int(self._rng.integers(2**32))):
238 for start in range(0, self.surrogate_budget, self.prediction_batch_size):
239 size = min(self.prediction_batch_size, self.surrogate_budget - start)
240 candidates = [search.ask() for _ in range(size)]
241 inputs = np.stack([self._encode(tuple(ind)) for ind in candidates])
242 self._predictions += size
243 y = np.asarray(self.surrogate.predict(inputs), dtype=float)
244 if y.shape != (size, len(low)) or not np.isfinite(y).all():
245 raise ValueError("Surrogate prediction needs one finite fitness/descriptor row per genome.")
246 for candidate, row in zip(candidates, np.clip(y, low, high)):
247 search.tell(candidate, fitness=(float(row[0]),), features=tuple(row[1:]))
248 self.last_surrogate_archive = imagined
249 return imagined
250
251
252 def run(self, evaluate, *, budget):
253 """Run initial and promoted measurements and return cumulative counters."""
254 budget = index(budget)
255 if budget < 0 or not callable(evaluate):
256 raise ValueError("Use a nonnegative budget and callable evaluate.")
257 stop = self._trials + budget
258 while len(self._inputs) < self.initial_samples and self._trials < stop:
259 self._measure(self._random(), evaluate)
260 while self._trials < stop:
261 auxiliary = None if self._auxiliary[0] is None else np.stack(self._auxiliary)
262 self._model_fits += 1
263 self.surrogate.fit(np.stack(self._inputs), np.asarray(self._targets), auxiliary)
264 imagined = self._illuminate()
265 selected = self._promote(imagined, min(self.simulation_batch_size, stop - self._trials))
266 for genome in selected or [self._random()]:
267 self._measure(genome, evaluate)
268 return self.stats
One true measurement with optional simulator observations.
Definition dsage.py:23
Separate ground-truth attempts, surrogate predictions, and model training calls.
Definition dsage.py:33
CPU neural surrogate with an optional first stage for ancillary observations.
Definition dsage.py:42
predict(self, x)
Predict fitness and descriptors for a batch of encoded genomes.
Definition dsage.py:115
fit(self, x, targets, auxiliary=None)
Fit fresh networks on measured targets and ancillary labels.
Definition dsage.py:61
Alternate measured simulations with illumination in a surrogate grid.
Definition dsage.py:133
_promote(self, predicted, limit)
Definition dsage.py:218
_encode(self, genome)
Definition dsage.py:185
_measure(self, genome, evaluate)
Definition dsage.py:193
run(self, evaluate, *, budget)
Spend a hard budget of additional true simulator calls.
Definition dsage.py:252
Fill a one-elite grid using Iso+LineDD variation.
Definition modern.py:56
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405