43 """Train a PyTorch MLP on encoded genome rows.
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.
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.")
57 self.
_seed = int(np.random.default_rng(seed).integers(2**32))
61 def fit(self, x, targets, auxiliary=None):
62 """Fit using input rows and targets ordered as fitness then descriptors."""
66 except ImportError
as error:
67 raise ImportError(
"The built-in DSAGE surrogate requires PyTorch.")
from error
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
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]
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"))
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):
100 prediction = model(x)
101 loss = (prediction - y).square().mean()
103 predicted_aux = ancillary(x)
104 prediction = model(torch.cat((x, predicted_aux), dim=1))
105 loss = (prediction - y).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)
112 self.
_model = model, ancillary, xm, xs, ym, ys
116 """Return a matrix in the original target units."""
118 raise RuntimeError(
"Fit the surrogate before predicting.")
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()
134 """Deep Surrogate Assisted Generation of Environments on fixed grids.
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.
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.
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.")
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")
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.")
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)
179 """Return the actual cumulative search costs."""
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.")
190 raise ValueError(
"The encoder must return a fixed number of values.")
191 return features.copy()
193 def _measure(self, genome, evaluate):
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.")
206 or (aux
is not None and aux.shape != self.
_auxiliary[0].shape)):
207 raise ValueError(
"All measurements must use the same auxiliary schema.")
210 and self.
archive.in_bounds(features, self.
archive.features_domain)):
211 cell = self.
archive.index_grid(features)
215 self.
_targets.append((value, *features))
218 def _promote(self, predicted, limit):
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]]
228 def _illuminate(self):
232 imagined =
Grid(shape=archive.shape, features_domain=archive.features_domain,
233 fitness_domain=archive.fitness_domain)
236 low, high = np.asarray((*archive.fitness_domain, *archive.features_domain)).T
237 with _coordinator_seed(int(self.
_rng.integers(2**32))):
240 candidates = [search.ask()
for _
in range(size)]
241 inputs = np.stack([self.
_encode(tuple(ind))
for ind
in candidates])
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:]))
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.")
266 for genome
in selected
or [self.
_random()]: