6"""Optional CPU PyTorch training for multi-container learned descriptors."""
8from copy
import deepcopy
9from dataclasses
import dataclass
10from itertools
import combinations
12from operator
import index
16from .feature_extraction
import TorchFeatureExtractionContainerDecorator
17from .grids
import Grid
25__all__ = [
"MCAurora",
"MCAuroraTraining"]
27_DIVERSITY_TERMS = (
"none",
"outputs",
"covariance",
"correlation")
33 """Flatten observations for encoding and restore their shape on decoding."""
35 def __init__(self, shape, latent_size):
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))
58@dataclass(frozen=True)
60 """One completed refit, with separate reconstruction and diversity terms.
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.
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()
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)
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()
105def _ensemble_losses(models, batch, term):
106 latents, outputs = [], []
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()
122 diversity = reconstruction.new_zeros(())
124 diversity = _latent_diversity(latents, term)
125 return reconstruction, diversity
131 """Coordinate a multi-container AURORA search on a shared observation depot.
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.
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.
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):
170 raise ImportError(
"MC-AURORA requires PyTorch. Install torch in this environment.")
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)
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)
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.")
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].")
213 raise ValueError(
"seed must be nonnegative.")
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)
233 grid.parents = [training_container]
236 for i, archive
in enumerate(self.
archives):
237 archive._initial_model_seed = (self.
seed + i) % (2**64)
242 """Register joint retraining after iterations and the final partial batch."""
244 algorithm.add_callback(
"finished_optimisation", self.
_on_iteration)
250 self.__dict__.update(state)
255 def _on_iteration(self, _algorithm, _elapsed):
261 """Train when the depot crosses a new multiple of the training period."""
265 if period
and count >= 2
and count // period > previous // period:
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
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)
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
298 def fit(self) -> MCAuroraTraining:
299 """Train the full ensemble from the current depot and rebuild its grids.
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.
307 raise ValueError(
"MC-AURORA needs at least two depot records.")
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.")
317 with torch.random.fork_rng(devices=[]):
319 models = [deepcopy(archive.model
if archive.model
is not None
320 else archive._make_default_model(sample[0])).cpu()
322 reconstruction, diversity, loss = self.
_train(models, data)
325 for archive, model
in zip(self.
archives, models):
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))
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)
344 optimizer = torch.optim.Adam((p
for model
in models
for p
in model.parameters()), lr=self.
learning_rate)
347 for _
in range(self.
epochs):
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:
352 batches[-1] = torch.cat((batches[-1], last))
353 for indices
in batches:
354 reconstruction, diversity = _ensemble_losses(models, data[indices], self.
diversity)
356 if not torch.isfinite(loss):
357 raise FloatingPointError(
"MC-AURORA produced a nonfinite loss.")
358 optimizer.zero_grad()
361 totals += np.asarray([reconstruction.item(), diversity.item(), loss.item()]) * len(indices)
362 return tuple(map(float, totals / len(data)))
Record the data size and mean losses from the final training epoch.
Train one encoder per grid and rebuild all learned archives together.
_stage_grid(self, archive, model, sample_tensor, records)
Encode with a candidate model and prepare a replacement grid.
MCAuroraTraining fit(self)
Fit model copies and stage every grid before installing the new descriptors.
__setstate__(self, state)
Restore the depot link when loading a saved coordinator.
_train(self, models, data)
Optimise the joint objective and average last-epoch batch losses.
MCAuroraTraining|None retrain_if_needed(self)
Fit once if the depot has crossed the next training threshold.
attach(self, algorithm)
Register scheduled retraining at iteration and final evaluation boundaries.
Dense MC-AURORA default with a smooth activation in the hidden layers.
forward(self, batch)
Reconstruct a batch in its original observation shape.
Use the same descriptor cache as single-archive AURORA.
_make_default_model(self, example_ind)
Create the independently initialised default model for this grid.
:param obj: Slice indicating on which objectives the domination is tested.