QDpy
Loading...
Searching...
No Matches
mc_aurora.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
3
5
6"""Optional CPU PyTorch training for multi-container learned descriptors."""
7
8from copy import deepcopy
9from dataclasses import dataclass
10from itertools import combinations
11import math
12from operator import index
13
14import numpy as np
15
16from .feature_extraction import TorchFeatureExtractionContainerDecorator
17from .grids import Grid
18from qdpy.phenotype import Features
19
20try:
21 import torch
22except ImportError:
23 torch = None
24
25__all__ = ["MCAurora", "MCAuroraTraining"]
26
27_DIVERSITY_TERMS = ("none", "outputs", "covariance", "correlation")
28
29
30if torch is not None:
31
32 class _EnsembleAutoencoder(torch.nn.Module):
33 """Flatten observations for encoding and restore their shape on decoding."""
34
35 def __init__(self, shape, latent_size):
36 super().__init__()
37 nn = torch.nn
38 size = math.prod(shape)
39 width = max(latent_size, min(128, max(size, 32)))
40 self.encoder = nn.Sequential(nn.Flatten(), nn.Linear(size, width), nn.SiLU(),
41 nn.Linear(width, latent_size))
42 self.decoder = nn.Sequential(nn.Linear(latent_size, width), nn.SiLU(),
43 nn.Linear(width, size), nn.Tanh(), nn.Unflatten(1, shape))
44
45
46 def forward(self, batch):
47 return self.decoder(self.encoder(batch))
48
49
50
57
58@dataclass(frozen=True)
60 """One completed refit, with separate reconstruction and diversity terms.
61
62 ``depot_size`` counts available records. ``sample_size`` counts records
63 actually used for training and quantile fitting. ``diversity`` is the
64 reward before applying the configured weight. ``loss`` is the
65 resulting mean training objective.
66 """
67
68 depot_size: int
69 sample_size: int
70 reconstruction: float
71 diversity: float
72 loss: float
73
74
75
78def _latent_diversity(latents, term):
79 if term == "covariance":
80 values = torch.cat(latents, dim=1)
81 centered = values - values.mean(dim=0)
82 covariance = centered.T @ centered / max(1, len(centered) - 1)
83 off_diagonal = ~torch.eye(len(covariance), dtype=torch.bool, device=covariance.device)
84 return -covariance[off_diagonal].abs().mean()
85
86 matrices = []
87 for latent in latents:
88 centered = latent - latent.mean(dim=0)
89 epsilon = torch.finfo(centered.dtype).eps
90 scaled = centered / torch.linalg.vector_norm(centered, dim=0).clamp_min(epsilon)
91 matrices.append(scaled.T @ scaled)
92 distances = []
93 for first, second in combinations(matrices, 2):
94 norm = torch.linalg.matrix_norm(first) * torch.linalg.matrix_norm(second)
95 similarity = (first * second).sum() / norm.clamp_min(epsilon)
96 distances.append(torch.where(norm > epsilon, (1 - similarity).clamp(0, 1), 0.))
97 return torch.stack(distances).mean()
98
99
100
105def _ensemble_losses(models, batch, term):
106 latents, outputs = [], []
107 for model in models:
108 dtype = next(model.parameters()).dtype
109 latent = model.encoder(batch.to(dtype=dtype))
110 if latent.ndim != 2 or len(latent) != len(batch) or latent.shape[1] == 0:
111 raise ValueError("Each encoder must return one latent vector per observation.")
112 decoded = model.decoder(latent)
113 if decoded.shape != batch.shape:
114 raise ValueError("Each decoder must reconstruct the input batch shape.")
115 latents.append(latent)
116 outputs.append(decoded)
117 outputs = torch.stack(outputs)
118 reconstruction = (outputs - batch).square().mean()
119 if term == "outputs":
120 diversity = (outputs - outputs.mean(dim=0)).square().mean()
121 elif term == "none":
122 diversity = reconstruction.new_zeros(())
123 else:
124 diversity = _latent_diversity(latents, term)
125 return reconstruction, diversity
126
127
128
131 """Coordinate a multi-container AURORA search on a shared observation depot.
132
133 Pass distinct, initially empty fixed grids and a separate training
134 container. Each wrapped grid forwards evaluated candidates to the
135 depot, including local rejects. Use ``archives`` as the containers of
136 ordinary ask/tell optimisers, for example with an alternating wrapper.
137 The coordinator keeps training and archive updates on the calling
138 thread. Evaluation workers only need to return fitness and observations.
139
140 :param grids: Fixed :class:`~qdpy.containers.Grid` instances to wrap.
141 :param training_container: Shared archive of evaluated observations.
142 :param base_scores: Ordered scalar score names to encode.
143 :param observation_score: Name of one fixed-shape numeric observation.
144 :param models: Optional autoencoder per grid, with encoder and decoder.
145 The default is a dense autoencoder with a tanh output.
146 :param training_period: Depot growth between scheduled refits.
147 A value of zero enables manual training only.
148 :param epochs: Training epochs per refit.
149 :param batch_size: Target training batch size.
150 :param learning_rate: Adam learning rate.
151 :param quantile_transform: Map latent coordinates into the unit interval.
152 :param diversity: One of ``none``, ``outputs``, ``covariance``, or ``correlation``.
153 :param diversity_weight: Weight subtracted times the diversity reward.
154 A positive weight penalises off-diagonal covariance.
155 :param rebuild_from: Reinsert the full ``depot`` into all grids or rebuild
156 from each grid's own ``elites``. An empty grid starts from the depot
157 on the first refit in either mode.
158 :param max_training_samples: Optional cap on records used per refit.
159 All rebuild records are encoded even when training uses a sample.
160 :param seed: Seed for model creation, training and depot sampling.
161 Seed the search RNG and any stochastic evaluator separately.
162 """
163
164 def __init__(self, grids, training_container, *, base_scores=None, observation_score=None,
165 models=None, training_period: int = 512, epochs: int = 5, batch_size: int = 128,
166 learning_rate: float = 1e-3, quantile_transform: bool = True, diversity: str = "none",
167 diversity_weight: float = 0., rebuild_from: str = "elites",
168 max_training_samples: int | None = None, seed: int = 0):
169 if torch is None:
170 raise ImportError("MC-AURORA requires PyTorch. Install torch in this environment.")
171 grids = tuple(grids)
172 if (len(grids) < 2 or len({id(grid) for grid in grids}) != len(grids)
173 or any(type(grid) is not Grid or len(grid) for grid in grids)):
174 raise ValueError("Pass at least two distinct, empty, fixed Grid instances.")
175 if (any(grid is training_container or grid.only_add_accepted_inds_to_parents for grid in grids)
176 or any(grid.parents and (len(grid.parents) != 1 or grid.parents[0] is not training_container)
177 for grid in grids)
178 or getattr(training_container, "parents", ())):
179 raise ValueError("The grids must forward all evaluations to one separate depot without parents.")
180 if (base_scores is None) == (observation_score is None):
181 raise ValueError("Specify either nonempty base_scores or an observation_score.")
182 if base_scores is not None:
183 base_scores = tuple(base_scores)
184 if not base_scores:
185 raise ValueError("base_scores cannot be empty.")
186 if (not isinstance(training_period, int) or training_period < 0
187 or not isinstance(epochs, int) or epochs < 1
188 or not isinstance(batch_size, int) or batch_size < 1
189 or not math.isfinite(learning_rate) or learning_rate <= 0):
190 raise ValueError("Use a nonnegative period and a positive epoch count, batch size and learning rate.")
191 if diversity not in _DIVERSITY_TERMS or not math.isfinite(diversity_weight):
192 raise ValueError(f"Use a finite diversity weight and one of {_DIVERSITY_TERMS}.")
193 if diversity == "correlation" and len({len(grid.features_domain) for grid in grids}) != 1:
194 raise ValueError("Correlation diversity requires equal latent widths.")
195 if rebuild_from not in ("elites", "depot"):
196 raise ValueError("Choose elites or depot as the rebuild source.")
197 if max_training_samples is not None and (
198 not isinstance(max_training_samples, int) or max_training_samples < 2):
199 raise ValueError("max_training_samples must be at least two.")
200 models = (None,) * len(grids) if models is None else tuple(models)
201 if len(models) != len(grids):
202 raise ValueError("Supply one model per grid.")
203 for model in models:
204 if model is not None and (not isinstance(model, torch.nn.Module)
205 or not callable(getattr(model, "encoder", None))
206 or not callable(getattr(model, "decoder", None))
207 or not any(p.requires_grad for p in model.parameters())):
208 raise ValueError("Each model needs an encoder, decoder and trainable parameters.")
209 if quantile_transform and any(any(lo > 0 or hi < 1 for lo, hi in grid.features_domain) for grid in grids):
210 raise ValueError("Quantile descriptors require grid domains containing [0, 1].")
211 seed = index(seed)
212 if seed < 0:
213 raise ValueError("seed must be nonnegative.")
214
215 self.training_container = training_container
216 self.training_period = training_period
217 self.epochs = epochs
218 self.batch_size = batch_size
219 self.learning_rate = learning_rate
220 self.diversity = diversity
221 self.diversity_weight = diversity_weight
222 self.rebuild_from = rebuild_from
223 self.max_training_samples = max_training_samples
224 self.seed = seed
225 self.training_history: list[MCAuroraTraining] = []
226 self.archives = tuple(
228 grid, model=deepcopy(model), base_scores=base_scores, observation_score=observation_score,
229 training_period=0, quantile_transform=quantile_transform)
230 for grid, model in zip(grids, models)
231 )
232 for grid in grids:
233 grid.parents = [training_container]
234 # Lazy provisional models may be needed before the first refit.
235 # They are seeded per archive without advancing the caller's RNG.
236 for i, archive in enumerate(self.archives):
237 archive._initial_model_seed = (self.seed + i) % (2**64)
238
239
241 def attach(self, algorithm):
242 """Register joint retraining after iterations and the final partial batch."""
243 algorithm.add_callback("iteration", self._on_iteration)
244 algorithm.add_callback("finished_optimisation", self._on_iteration)
245
246
249 def __setstate__(self, state):
250 self.__dict__.update(state)
251 for archive in self.archives:
252 archive.container.parents = [self.training_container]
253
254
255 def _on_iteration(self, _algorithm, _elapsed):
256 self.retrain_if_needed()
257
258
260 def retrain_if_needed(self) -> MCAuroraTraining | None:
261 """Train when the depot crosses a new multiple of the training period."""
262 period = self.training_period
263 previous = self.training_history[-1].depot_size if self.training_history else 0
264 count = len(self.training_container)
265 if period and count >= 2 and count // period > previous // period:
266 return self.fit()
267 return None
268
269
272 def _stage_grid(self, archive, model, sample_tensor, records):
273 latent = archive._encode(model, sample_tensor)
274 if latent.shape[1] != len(archive.features_domain):
275 raise ValueError("The encoder width must match the grid descriptor domain.")
276 transformer = archive._fit_quantile_transform(latent) if archive.quantile_transform else None
277 rows = []
278 for start in range(0, len(records), self.batch_size):
279 batch = archive._score_tensor(records[start:start + self.batch_size])
280 rows.extend(archive._transform_latent(archive._encode(model, batch), transformer).tolist())
281 descriptors = {id(ind): Features(row) for ind, row in zip(records, rows)}
282 grid = archive.container
283 memo = {id(entry): entry for entry in grid}
284 memo.update({id(archive): archive, id(grid.parents): grid.parents})
285 staged = deepcopy(grid, memo)
286 staged.parents = []
287 staged.clear()
288 staged.get_ind_features = lambda ind: descriptors[id(ind)]
289 staged.update(records, ignore_exceptions=False)
290 staged.parents = grid.parents
291 staged.get_ind_features = grid.get_ind_features
292 return staged, transformer, rows
293
294
298 def fit(self) -> MCAuroraTraining:
299 """Train the full ensemble from the current depot and rebuild its grids.
300
301 The live models, grids and training history are installed only after
302 training, encoding and staged readmission succeed for every grid.
303 Train and call ask/tell serially on the coordinator.
304 """
305 depot = list(self.training_container)
306 if len(depot) < 2:
307 raise ValueError("MC-AURORA needs at least two depot records.")
308 rng = np.random.default_rng([self.seed, len(self.training_history)])
309 sample = depot
310 if self.max_training_samples is not None and len(depot) > self.max_training_samples:
311 sampled = np.sort(rng.choice(len(depot), self.max_training_samples, replace=False))
312 sample = [depot[i] for i in sampled]
313 data = self.archives[0]._score_tensor(sample).detach()
314 if not torch.isfinite(data).all():
315 raise ValueError("Training observations must be finite.")
316
317 with torch.random.fork_rng(devices=[]):
318 torch.random.default_generator.manual_seed((self.seed + len(self.training_history)) % (2**64))
319 models = [deepcopy(archive.model if archive.model is not None
320 else archive._make_default_model(sample[0])).cpu()
321 for archive in self.archives]
322 reconstruction, diversity, loss = self._train(models, data)
323
324 staged_grids = []
325 for archive, model in zip(self.archives, models):
326 use_depot = self.rebuild_from == "depot" or (not self.training_history and not len(archive))
327 records = depot if use_depot else list(archive)
328 staged, transform, rows = self._stage_grid(archive, model, data, records)
329 staged_grids.append((staged, transform, records, rows))
330
331 for archive, model, (staged, transform, records, rows) in zip(self.archives, models, staged_grids):
332 archive.model = model
333 archive._quantile_transformer = transform
334 archive._descriptor_version += 1
335 archive._store_descriptors(records, rows)
336 archive.container.__dict__.update(staged.__dict__)
337 archive.container.features_score_names = archive._extracted_score_names()
338 result = MCAuroraTraining(len(depot), len(sample), reconstruction, diversity, loss)
339 self.training_history.append(result)
340 return result
341
342
343 def _train(self, models, data):
344 optimizer = torch.optim.Adam((p for model in models for p in model.parameters()), lr=self.learning_rate)
345 for model in models:
346 model.train()
347 for _ in range(self.epochs):
348 totals = np.zeros(3)
349 batches = list(torch.randperm(len(data)).split(self.batch_size))
350 if self.batch_size > 1 and len(batches) > 1 and len(batches[-1]) == 1:
351 last = batches.pop()
352 batches[-1] = torch.cat((batches[-1], last))
353 for indices in batches:
354 reconstruction, diversity = _ensemble_losses(models, data[indices], self.diversity)
355 loss = reconstruction - self.diversity_weight * diversity
356 if not torch.isfinite(loss):
357 raise FloatingPointError("MC-AURORA produced a nonfinite loss.")
358 optimizer.zero_grad()
359 loss.backward()
360 optimizer.step()
361 totals += np.asarray([reconstruction.item(), diversity.item(), loss.item()]) * len(indices)
362 return tuple(map(float, totals / len(data)))
_input_shape(self, example_ind)
Infer the shape of a score vector or array-valued observation.
Record the data size and mean losses from the final training epoch.
Definition mc_aurora.py:59
Train one encoder per grid and rebuild all learned archives together.
Definition mc_aurora.py:130
_stage_grid(self, archive, model, sample_tensor, records)
Encode with a candidate model and prepare a replacement grid.
Definition mc_aurora.py:272
MCAuroraTraining fit(self)
Fit model copies and stage every grid before installing the new descriptors.
Definition mc_aurora.py:298
__setstate__(self, state)
Restore the depot link when loading a saved coordinator.
Definition mc_aurora.py:249
_train(self, models, data)
Optimise the joint objective and average last-epoch batch losses.
Definition mc_aurora.py:343
MCAuroraTraining|None retrain_if_needed(self)
Fit once if the depot has crossed the next training threshold.
Definition mc_aurora.py:260
attach(self, algorithm)
Register scheduled retraining at iteration and final evaluation boundaries.
Definition mc_aurora.py:241
Dense MC-AURORA default with a smooth activation in the hidden layers.
Definition mc_aurora.py:32
forward(self, batch)
Reconstruct a batch in its original observation shape.
Definition mc_aurora.py:46
Use the same descriptor cache as single-archive AURORA.
Definition mc_aurora.py:51
_make_default_model(self, example_ind)
Create the independently initialised default model for this grid.
Definition mc_aurora.py:53
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405