73 """Train a latent encoder on live elites, with separate ablation settings.
75 Use loss="triplet" for contrastive training or "reconstruction" for plain
76 autoencoding. A positive extinction_period retains the best member and a
77 seeded random subset of others. The active archive is rebuilt after each
78 refit. Keep any external reporting archives in the evaluator so they do
79 not feed discarded records back into search or training.
81 :param dimension: Length of the bounded real genome.
82 :param latent_size: Width of the learned descriptor.
83 :param ind_domain: Shared bounds on real parameters.
84 :param capacity: Maximum active repertoire size.
85 :param radius: Initial nearest-neighbour replacement radius in latent coordinates.
86 :param target_size: Desired live repertoire size. Defaults to half capacity, capped at 32.
87 :param size_gain: Relative proportional gain for radius adjustment. Zero fixes the radius.
88 :param loss: "triplet" or "reconstruction".
89 :param initial_samples: Uniform attempts used for the first encoder fit.
90 :param training_period: Attempted evaluations between later refits.
91 :param extinction_period: Attempts after warmup between prunings. Zero disables pruning.
92 :param survival_fraction: Fraction to retain randomly, in addition to the best.
93 :param epochs: Training passes per refit.
94 :param batch_size: Maximum observations or triplets per training update.
95 :param learning_rate: Adam step size, with fresh moments at each refit.
96 :param iso_sigma: Iso+LineDD independent noise scale.
97 :param line_sigma: Iso+LineDD direction scale.
98 :param seed: Seed for proposals, evaluator calls, and training.
99 :param device: PyTorch device, CPU by default.
102 def __init__(self, dimension, *, latent_size=2, ind_domain=(0., 1.), capacity=256, radius=.1, loss=
"triplet",
103 target_size=
None, size_gain=.05,
104 initial_samples=24, training_period=32, extinction_period=128, survival_fraction=.05,
105 epochs=4, batch_size=16, learning_rate=1e-3, iso_sigma=.05, line_sigma=.2, seed=0, device=
"cpu"):
106 if mc_aurora.torch
is None:
107 raise ImportError(
"AuroraXCon requires PyTorch. Install qdpy[rl] or torch.")
108 if loss
not in (
"triplet",
"reconstruction"):
109 raise ValueError(
"Choose triplet or reconstruction loss.")
110 if not (0. < radius < np.inf
and 0. < learning_rate < np.inf
111 and 0. <= survival_fraction <= 1.
and 0. <= size_gain <= 1.):
112 raise ValueError(
"Use finite positive radius and learning_rate and fractions and gains in [0, 1].")
113 self.
_dimension = _positive_int(dimension,
"dimension")
114 self.
_latent_size = _positive_int(latent_size,
"latent_size")
115 self.
_bounds = _variation_settings(ind_domain, iso_sigma, line_sigma)
117 raise ValueError(
"Use a finite decision interval width.")
118 self.
_capacity = _positive_int(capacity,
"capacity")
120 else _positive_int(target_size,
"target_size"))
122 raise ValueError(
"target_size must fit within capacity.")
124 self.
_warmup = _positive_int(initial_samples,
"initial_samples")
125 self.
_train_period = _positive_int(training_period,
"training_period")
126 self.
_extinction_period = (0
if extinction_period == 0
else _positive_int(extinction_period,
127 "extinction_period"))
128 self.
_epochs = _positive_int(epochs,
"epochs")
129 self.
_batch_size = _positive_int(batch_size,
"batch_size")
133 self.
_rng = np.random.default_rng(seed)
135 np.random.default_rng(s)
for s
in np.random.SeedSequence(seed).spawn(3))
136 self.
_device = mc_aurora.torch.device(device)
140 self.
_counts = dict(evaluations=0, failed_evaluations=0, archive_updates=0, refits=0, optimizer_steps=0,
141 extinctions=0, pruned=0)
145 """Return cumulative costs and changes since construction."""
148 def _new_archive(self):
151 def _tensor(self, points):
152 return mc_aurora.torch.as_tensor(points, dtype=mc_aurora.torch.float32, device=self.
_device)
154 def _rows(self, records):
155 return self.
_tensor(np.stack([record.scores[_OBSERVATION]
for record
in records]))
157 def _embeddings(self, model, points):
158 with mc_aurora.torch.no_grad():
159 values = model.encoder(points).cpu().numpy()
160 if not np.isfinite(values).all():
161 raise ValueError(
"The encoder produced nonfinite descriptors.")
164 def _new_model(self):
165 torch = mc_aurora.torch
166 with torch.random.fork_rng(devices=[]):
167 torch.random.default_generator.manual_seed(int(self.
_training.integers(2**32)))
169 device=self.
_device, dtype=torch.float32)
171 def _triplets(self, qualities):
173 ids = np.arange(len(qualities))
174 first = self.
_training.integers(len(ids) - 1, size=len(ids))
175 first += first >= ids
176 second = self.
_training.integers(len(ids) - 2, size=len(ids))
177 second += second >= np.minimum(first, ids)
178 second += second >= np.maximum(first, ids)
179 distances = np.abs(qualities[:,
None] * .5 - qualities[np.column_stack((first, second))] * .5)
180 distinct = distances[:, 0] != distances[:, 1]
181 swap = distances[:, 0] > distances[:, 1]
182 return np.column_stack((ids, np.where(swap, second, first), np.where(swap, first, second)))[distinct]
184 def _train_encoder(self, model, points, qualities):
185 torch = mc_aurora.torch
186 optimizer = torch.optim.Adam(model.parameters(), lr=self.
_rate)
187 if self.
_loss ==
"triplet" and len(points) < 3:
190 if self.
_loss ==
"triplet":
192 margin = float(max(np.min(pairs), np.finfo(np.float32).eps))
195 rows = np.arange(len(points))
196 rows = rows[self.
_training.permutation(len(rows))]
197 for start
in range(0, len(rows), self.
_batch_size):
199 if self.
_loss ==
"triplet":
200 values = model.encoder(points[indices.reshape(-1)]).reshape(-1, 3, self.
_latent_size)
201 anchor, near, far = values.unbind(1)
202 loss = (torch.linalg.vector_norm(anchor - near, dim=1) -
203 torch.linalg.vector_norm(anchor - far, dim=1) + margin).clamp_min(0).mean()
205 batch = points[indices]
206 loss = (model(batch) - batch).square().mean()
207 if not torch.isfinite(loss):
208 raise ValueError(
"The encoder loss is nonfinite.")
209 optimizer.zero_grad()
212 self.
_counts[
"optimizer_steps"] += 1
214 def _refit(self, records):
216 points = self.
_rows(records)
217 qualities = np.asarray([row.fitness.values[0]
for row
in records])
218 with mc_aurora.torch.enable_grad():
224 first = int(np.argmax(qualities))
225 for i
in (first, *(j
for j
in range(len(records))
if j != first)):
227 rebuilt.add(
Individual(row, fitness=row.fitness, features=
Features(tuple(descriptors[i])),
228 scores={_OBSERVATION: row.scores[_OBSERVATION]}))
234 others = [row
for row
in self.
archive if row
is not self.
archive.best]
236 keep = set(map(int, self.
_pruning.choice(len(others), size=size, replace=
False)))
237 for i, row
in enumerate(others):
240 self.
_counts[
"extinctions"] += 1
243 def _adapt_radius(self):
248 def _record(self, genome, reward, trajectory):
249 quality = np.asarray(reward, dtype=float)
250 points = np.array(trajectory, dtype=np.float32, copy=
True)
251 if (quality.shape
not in ((), (1,))
or not np.isfinite(quality).all()
or points.ndim != 2
252 or not points.size
or not np.isfinite(points).all()
or (np.abs(points) > 1).any()
253 or (self.
_shape is not None and self.
_shape != points.shape)):
254 raise ValueError(
"Return finite scalar fitness and a fixed-shape trajectory scaled to [-1, 1].")
255 self.
_shape = points.shape
256 points.setflags(write=
False)
257 record =
Individual(genome, fitness=
Fitness((float(quality.item()),), weights=(1.,)),
258 scores={_OBSERVATION: points})
263 previous = self.
archive.nb_added
265 self.
_counts[
"archive_updates"] += self.
archive.nb_added - previous
267 def _refresh_representation(self):
284 def run(self, evaluate, budget):
285 """Measure one trajectory per proposal and charge failed attempts."""
286 for _
in range(_positive_int(budget,
"budget")):
287 calls = self.
_counts[
"evaluations"]
291 first, second = self.
_rng.integers(len(self.
archive), size=2)
294 genome = tuple(map(float, genome))
295 self.
_counts[
"evaluations"] += 1
296 measurement = evaluate(genome, int(self.
_rollouts.integers(2**32)))
297 if measurement
is None:
298 self.
_counts[
"failed_evaluations"] += 1
300 self.
_record(genome, *measurement)