56 """Measure and commit complete seeded generations with optional observations."""
58 def __init__(self, dimension, *, ind_domain, population_size, offspring, mutation_sigma,
59 embedding_size, epochs, batch_size, learning_rate, seed, device):
60 if mc_aurora.torch
is None:
61 raise ImportError(
"Learned exploration requires PyTorch. Install PyTorch or qdpy[rl].")
62 self.
_torch = mc_aurora.torch
64 self.
_dimension = _positive_int(dimension,
"dimension")
66 self.
_offspring = _positive_int(offspring,
"offspring")
67 self.
_epochs = _positive_int(epochs,
"epochs")
68 self.
_batch_size = _positive_int(batch_size,
"batch_size")
70 self.
_bounds = _bounds(ind_domain)
73 if not (0 < self.
_scale < np.inf
and 0 < learning_rate < np.inf):
74 raise ValueError(
"Mutation and learning rates must be finite and positive.")
75 self.
_rate = learning_rate
77 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
86 """Return the most recent committed exploration population."""
91 """Return cumulative search costs and completed generations."""
94 def _initialize_model(self):
96 with torch.random.fork_rng(devices=[]):
97 torch.random.default_generator.manual_seed(int(self.
_training.integers(2**32)))
98 self.
_model = self._build_model()
101 def _observation(self, observation):
102 values = np.array(observation, dtype=np.float32, copy=
True)
103 if (
not values.ndim
or not values.size
or not np.all(np.isfinite(values))
104 or (self.
_shape is not None and values.shape != self.
_shape)):
105 raise ValueError(
"Use a finite observation array of fixed nonempty shape.")
108 def _tensor(self, observations):
111 def _measure(self, evaluate, parent, sigma, counter):
117 genome = tuple(point.tolist())
119 result = evaluate(genome, int(self.
_rollouts.integers(2**32)))
121 self.
_counts[
"failed_evaluations"] += 1
123 reward, observation = result
124 reward = float(reward)
125 if not np.isfinite(reward):
126 raise ValueError(
"Return a finite scalar reward.")
128 values.setflags(write=
False)
130 self.
_shape = values.shape
134 def _fit(self, records, objective):
137 points = self.
_tensor(np.stack([row.observation
for row
in records]))
138 with self.
_torch.enable_grad():
140 order = self.
_training.permutation(len(points))
141 for offset
in range(0, len(points), self.
_batch_size):
142 loss = objective(points[order[offset:offset + self.
_batch_size]])
143 if not self.
_torch.isfinite(loss):
144 raise ValueError(
"The observation model's training loss is nonfinite.")
148 self.
_counts[
"model_updates"] += 1
150 def _explore(self, evaluate):
152 row = self.
_measure(evaluate, parent, self.
_scale,
"exploration_evaluations")
160 self._commit_exploration(self.
_pending)
162 self.
_counts[
"generations"] += 1
165 def _advance(self, evaluate):
172 def run(self, evaluate, budget):
173 """Continue from the last generation, including any pending measurements."""
174 if not callable(evaluate):
175 raise TypeError(
"evaluate must be callable.")
176 for _
in range(_attempt_budget(budget)):
183 """Use latent k-nearest-neighbor novelty and reconstruction error.
185 Choose one criterion with equal probability for each generation.
186 Add the strongest novel offspring to a bounded archive. Fit on a
187 bounded cache of measured observations between generations.
189 :param dimension: Number of real parameters per genome.
190 :param ind_domain: Common inclusive genome bounds.
191 :param population_size: Maximum number of breeding policies.
192 :param offspring: Number of evaluations per generation after initialization.
193 :param mutation_sigma: Gaussian strength as a fraction of the bounds' span.
194 :param latent_size: Learned descriptor width.
195 :param neighbors: Neighbors contributing to each novelty score.
196 :param novelty_capacity: Maximum number of retained novelty records.
197 :param archive_additions: Maximum new records retained per generation.
198 :param training_capacity: Maximum number of recent training observations.
199 :param epochs: Reconstruction training epochs per completed generation.
200 :param batch_size: Maximum observations per training minibatch.
201 :param learning_rate: Adam learning rate.
202 :param seed: Private rollout, variation and training seed.
203 :param device: PyTorch device.
206 def __init__(self, dimension, *, ind_domain=(0., 1.), population_size=16, offspring=16, mutation_sigma=.12,
207 latent_size=3, neighbors=8, novelty_capacity=128, archive_additions=2, training_capacity=128,
208 epochs=2, batch_size=32, learning_rate=1e-3, seed=0, device=
"cpu"):
209 super().__init__(dimension, ind_domain=ind_domain, population_size=population_size, offspring=offspring,
210 mutation_sigma=mutation_sigma, embedding_size=latent_size, epochs=epochs,
211 batch_size=batch_size, learning_rate=learning_rate, seed=seed, device=device)
212 self.
_neighbors = _positive_int(neighbors,
"neighbors")
213 self.
_additions = _positive_int(archive_additions,
"archive_additions")
214 self.
_memory = deque(maxlen=_positive_int(novelty_capacity,
"novelty_capacity"))
215 self.
_training_rows = deque(maxlen=_positive_int(training_capacity,
"training_capacity"))
219 """Return measured observations retained for latent novelty."""
222 def _build_model(self):
226 def _observation(self, observation):
227 values = super()._observation(observation)
228 if np.any(np.abs(values) > 1.):
229 raise ValueError(
"Scale autoencoder observations to [-1, 1].")
232 def _model_scores(self, values):
234 with self.
_torch.no_grad():
235 latent = self.
_model.encoder(batch)
236 error = (self.
_model.decoder(latent) - batch).square().reshape(len(batch), -1).mean(dim=1)
237 return latent.cpu().numpy(), error.cpu().numpy()
241 """Return the current latent descriptor of one previously measurable observation."""
243 raise RuntimeError(
"Evaluate an observation before encoding.")
246 def _latent_novelty(self, rows, reference):
248 return np.zeros(len(rows))
249 combined = list(dict.fromkeys((*rows, *reference)))
250 with self.
_torch.no_grad():
251 latent = self.
_model.encoder(self.
_tensor(np.stack([row.observation
for row
in combined]))).cpu().numpy()
252 indices = {row: i
for i, row
in enumerate(combined)}
253 sources = [indices[row]
for row
in rows]
254 targets = [indices[row]
for row
in reference]
255 return self.
_nearest(latent[sources], latent[targets], sources, targets)
257 def _nearest(self, source, target, source_ids, target_ids):
258 distances = cdist(source, target)
259 distances[np.equal.outer(source_ids, target_ids)] = np.inf
261 nearest = np.partition(distances, k - 1, axis=1)[:, :k]
262 available = np.isfinite(nearest)
263 return np.where(available, nearest, 0.).sum(axis=1) / np.maximum(1, available.sum(axis=1))
265 def _rank(self, scores):
266 return np.argsort(-scores[:, int(self.
_variation.integers(2))], kind=
"stable")
268 def _commit_exploration(self, children):
270 reference = list(dict.fromkeys((*pool, *self.
_memory)))
271 latent, errors = self.
_model_scores(np.stack([row.observation
for row
in reference]))
272 novelty = self.
_nearest(latent[:len(pool)], latent, range(len(pool)), range(len(reference)))
273 scores = np.column_stack((novelty, errors[:len(pool)]))
275 ranked = self.
_rank(scores)
276 survivors = [int(i) - start
for i
in ranked
if i >= start]
281 self.
_fit(training,
lambda batch: (self.
_model(batch) - batch).square().mean())
285 """Learn behavior from observations while exploiting sparse reward discoveries.
287 A successful evaluation can seed an emitter with reward-only survival.
288 Promising bootstrap emitters continue on a novelty/improvement Pareto
289 front. Model refits reuse measured observations. The reward archive
290 stores observations and genomes independently of the current latent
293 :param dimension: Number of real parameters per genome.
294 :param reward_threshold: Seed and retain policies with reward strictly above this value.
295 :param emitter_budget: Maximum reward-search calls after each exploration generation.
296 :param emitter_sigma: Local mutation strength as a fraction of the genome span.
297 :param emitter_size: Maximum number of parents per emitter.
298 :param bootstrap_calls: Calls before accepting an improving emitter.
299 :param stagnation_calls: Nonimproving calls before retiring an active emitter.
300 :param max_emitters: Bound on each queue and the active emitter pool.
301 :param reward_capacity: Maximum retained reward records.
302 :param kwargs: TAXONS representation and exploration settings.
305 def __init__(self, dimension, *, reward_threshold=0., emitter_budget=16, emitter_sigma=.03, emitter_size=4,
306 bootstrap_calls=4, stagnation_calls=20, max_emitters=8, reward_capacity=128, **kwargs):
307 super().__init__(dimension, **kwargs)
309 if not (np.isfinite(reward_threshold)
and 0. < self.
_emitter_scale < np.inf):
310 raise ValueError(
"Use a finite threshold and finite positive emitter mutation scale.")
312 self.
_emitter_size = _positive_int(emitter_size,
"emitter_size")
314 self.
_stagnation = _positive_int(stagnation_calls,
"stagnation_calls")
315 self.
_limit = _positive_int(max_emitters,
"max_emitters")
316 self.
_reward = deque(maxlen=_positive_int(reward_capacity,
"reward_capacity"))
322 """Return the bounded reward archive in measurement order."""
325 def _rank(self, scores):
326 return _nsga_order(scores, len(scores))[0]
328 def _commit_exploration(self, children):
329 super()._commit_exploration(children)
338 def _measure(self, evaluate, parent, sigma, counter):
339 row = super()._measure(evaluate, parent, sigma, counter)
344 def _select_emitter(self):
350 self.
_counts[
"emitters_started"] += 1
355 scores = np.column_stack((novelty, [emitter.improvement
for emitter
in self.
_active]))
358 def _advance(self, evaluate):
364 probing = emitter
is self.
_probe
365 best = emitter.population[0]
366 parent = emitter.population[int(self.
_variation.integers(len(emitter.population)))]
368 "bootstrap_evaluations" if probing
else "emitter_evaluations")
371 emitter.population.append(row)
372 emitter.population.sort(key=
lambda item: item.reward, reverse=
True)
374 if row.reward > best.reward:
375 gain = row.reward - best.reward
382 emitter.improvement += gain
385 if emitter.improvement > 0.:
387 weakest = min(range(len(self.
_active)), key=
lambda i: self.
_active[i].improvement)
392 emitter.improvement = .9 * emitter.improvement + .1 * gain
393 emitter.stalls = 0
if gain
else emitter.stalls + 1
401 """Run archive-free Behavior Recognition Novelty Search.
403 Score candidates with squared embedding prediction error before
404 training on the generation's newly measured observations. Use a
405 slightly deeper predictor with leaky ReLU and a linear output layer.
406 The retained population and the unfinished generation bound memory.
408 :param dimension: Number of real parameters per genome.
409 :param ind_domain: Common inclusive genome bounds.
410 :param population_size: Maximum breeding population.
411 :param offspring: Candidate evaluations in subsequent generations.
412 :param mutation_sigma: Gaussian strength as a fraction of the bounds' span.
413 :param embedding_size: Width of the fixed random embedding.
414 :param hidden_size: Width of the target and predictor hidden layers.
415 :param epochs: Prediction training epochs per generation.
416 :param batch_size: Maximum observations per optimization step.
417 :param learning_rate: Adam learning rate.
418 :param seed: Private rollout, variation and training seed.
419 :param device: PyTorch device.
422 def __init__(self, dimension, *, ind_domain=(0., 1.), population_size=16, offspring=16, mutation_sigma=.12,
423 embedding_size=32, hidden_size=64, epochs=2, batch_size=32, learning_rate=1e-3,
424 seed=0, device=
"cpu"):
425 super().__init__(dimension, ind_domain=ind_domain, population_size=population_size, offspring=offspring,
426 mutation_sigma=mutation_sigma, embedding_size=embedding_size, epochs=epochs,
427 batch_size=batch_size, learning_rate=learning_rate, seed=seed, device=device)
428 self.
_hidden = _positive_int(hidden_size,
"hidden_size")
431 def _build_model(self):
436 nn.Flatten(), nn.Linear(width, hidden), nn.LeakyReLU(), nn.Linear(hidden, self.
_embedding_size)
437 ).to(device=self.
_device, dtype=self.
_torch.float32).requires_grad_(
False)
438 return nn.Sequential(nn.Flatten(), nn.Linear(width, hidden), nn.LeakyReLU(),
439 nn.Linear(hidden, hidden), nn.LeakyReLU(),
442 def _scores(self, points):
443 return (self.
_model(points) - self.
_target(points)).square().sum(dim=1)
447 """Return squared prediction error for the observation."""
449 raise RuntimeError(
"Evaluate an observation before scoring novelty.")
450 with self.
_torch.no_grad():
453 def _commit_exploration(self, children):
455 with self.
_torch.no_grad():
456 scores = self.
_scores(self.
_tensor(np.stack([row.observation
for row
in pool]))).cpu().numpy()
459 self.
_fit(children,
lambda batch: self.
_scores(batch).mean())