# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Novelty search with online sensory representations or behavior recognition.
# @see https://doi.org/10.1109/ICRA40945.2020.9196819
# @see https://doi.org/10.1162/evco_a_00343
# @see https://doi.org/10.1145/3449639.3459303
"""Run TAXONS, STAX, or BR-NS with bounded observation memory."""
from collections import Counter, deque
from dataclasses import dataclass
from math import prod
import numpy as np
from scipy.spatial.distance import cdist
from qdpy.containers import mc_aurora
from ._population import _attempt_budget, _nsga_order, _pareto_fronts
from .modern import _bounds, _positive_int
from .serene import _Emitter
__all__ = ["BRNS", "LearnedBehavior", "LearnedExplorationStats", "STAX", "TAXONS"]
## @brief One measured candidate with its unchanged observation.
[docs]
@dataclass(frozen=True, eq=False)
class LearnedBehavior:
"""Keep the numeric genome, reward, and a read-only observation array."""
genome: tuple[float, ...]
reward: float
observation: np.ndarray
## @brief Count exploration, reward exploitation and model fitting separately.
[docs]
@dataclass(frozen=True)
class LearnedExplorationStats:
"""Candidate attempts include failures and prefixes of pending generations."""
exploration_evaluations: int = 0
bootstrap_evaluations: int = 0
emitter_evaluations: int = 0
failed_evaluations: int = 0
model_updates: int = 0
generations: int = 0
emitters_started: int = 0
first_reward_evaluation: int | None = None
@property
def evaluations(self):
"""Return the total number of evaluator calls."""
return self.exploration_evaluations + self.bootstrap_evaluations + self.emitter_evaluations
class _ObservationSearch:
"""Measure and commit complete seeded generations with optional observations."""
def __init__(self, dimension, *, ind_domain, population_size, offspring, mutation_sigma,
embedding_size, epochs, batch_size, learning_rate, seed, device):
if mc_aurora.torch is None:
raise ImportError("Learned exploration requires PyTorch. Install PyTorch or qdpy[rl].")
self._torch = mc_aurora.torch
self._device = self._torch.device(device)
self._dimension = _positive_int(dimension, "dimension")
self._population_size = _positive_int(population_size, "population_size")
self._offspring = _positive_int(offspring, "offspring")
self._epochs = _positive_int(epochs, "epochs")
self._batch_size = _positive_int(batch_size, "batch_size")
self._embedding_size = _positive_int(embedding_size, "embedding_size")
self._bounds = _bounds(ind_domain)
self._span = self._bounds[1] - self._bounds[0]
self._scale = self._span * mutation_sigma
if not (0 < self._scale < np.inf and 0 < learning_rate < np.inf):
raise ValueError("Mutation and learning rates must be finite and positive.")
self._rate = learning_rate
self._variation, self._rollouts, self._training = map(
np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
self._shape, self._model, self._optimizer = None, None, None
self._population, self._pending = [], []
self._pending_calls = 0
self._counts = Counter()
self._first_reward = None
@property
def population(self):
"""Return the most recent committed exploration population."""
return tuple(self._population)
@property
def stats(self):
"""Return cumulative search costs and completed generations."""
return LearnedExplorationStats(**self._counts, first_reward_evaluation=self._first_reward)
def _initialize_model(self):
torch = self._torch
with torch.random.fork_rng(devices=[]):
torch.random.default_generator.manual_seed(int(self._training.integers(2**32)))
self._model = self._build_model()
self._optimizer = torch.optim.Adam(self._model.parameters(), lr=self._rate)
def _observation(self, observation):
values = np.array(observation, dtype=np.float32, copy=True)
if (not values.ndim or not values.size or not np.all(np.isfinite(values))
or (self._shape is not None and values.shape != self._shape)):
raise ValueError("Use a finite observation array of fixed nonempty shape.")
return values
def _tensor(self, observations):
return self._torch.as_tensor(observations, device=self._device, dtype=self._torch.float32)
def _measure(self, evaluate, parent, sigma, counter):
if parent is None:
point = self._variation.uniform(*self._bounds, size=self._dimension)
else:
point = np.clip(np.asarray(parent.genome) + self._variation.normal(0., sigma, self._dimension),
*self._bounds)
genome = tuple(point.tolist())
self._counts[counter] += 1
result = evaluate(genome, int(self._rollouts.integers(2**32)))
if result is None:
self._counts["failed_evaluations"] += 1
return None
reward, observation = result
reward = float(reward)
if not np.isfinite(reward):
raise ValueError("Return a finite scalar reward.")
values = self._observation(observation)
values.setflags(write=False)
if self._model is None:
self._shape = values.shape
self._initialize_model()
return LearnedBehavior(genome, reward, values)
def _fit(self, records, objective):
if not records:
return
points = self._tensor(np.stack([row.observation for row in records]))
with self._torch.enable_grad():
for _ in range(self._epochs):
order = self._training.permutation(len(points))
for offset in range(0, len(points), self._batch_size):
loss = objective(points[order[offset:offset + self._batch_size]])
if not self._torch.isfinite(loss):
raise ValueError("The observation model's training loss is nonfinite.")
self._optimizer.zero_grad()
loss.backward()
self._optimizer.step()
self._counts["model_updates"] += 1
def _explore(self, evaluate):
parent = self._population[int(self._variation.integers(len(self._population)))] if self._population else None
row = self._measure(evaluate, parent, self._scale, "exploration_evaluations")
if row is not None:
self._pending.append(row)
self._pending_calls += 1
generation_size = self._offspring if self._population else self._population_size
if self._pending_calls < generation_size:
return False
if self._pending:
self._commit_exploration(self._pending)
self._pending, self._pending_calls = [], 0
self._counts["generations"] += 1
return True
def _advance(self, evaluate):
self._explore(evaluate)
## @brief Measure another hard budget while retaining partial generations.
# @param evaluate Callback (genome, seed) returning (reward, observation) or None.
# @param budget Number of additional evaluator calls, including failures.
# @return Cumulative LearnedExplorationStats.
def run(self, evaluate, budget):
"""Continue from the last generation, including any pending measurements."""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
for _ in range(_attempt_budget(budget)):
self._advance(evaluate)
return self.stats
## @brief Learn an outcome space with an autoencoder and explore by novelty or surprise.
[docs]
class TAXONS(_ObservationSearch):
"""Use latent k-nearest-neighbor novelty and reconstruction error.
Choose one criterion with equal probability for each generation.
Add the strongest novel offspring to a bounded archive. Fit on a
bounded cache of measured observations between generations.
:param dimension: Number of real parameters per genome.
:param ind_domain: Common inclusive genome bounds.
:param population_size: Maximum number of breeding policies.
:param offspring: Number of evaluations per generation after initialization.
:param mutation_sigma: Gaussian strength as a fraction of the bounds' span.
:param latent_size: Learned descriptor width.
:param neighbors: Neighbors contributing to each novelty score.
:param novelty_capacity: Maximum number of retained novelty records.
:param archive_additions: Maximum new records retained per generation.
:param training_capacity: Maximum number of recent training observations.
:param epochs: Reconstruction training epochs per completed generation.
:param batch_size: Maximum observations per training minibatch.
:param learning_rate: Adam learning rate.
:param seed: Private rollout, variation and training seed.
:param device: PyTorch device.
"""
def __init__(self, dimension, *, ind_domain=(0., 1.), population_size=16, offspring=16, mutation_sigma=.12,
latent_size=3, neighbors=8, novelty_capacity=128, archive_additions=2, training_capacity=128,
epochs=2, batch_size=32, learning_rate=1e-3, seed=0, device="cpu"):
super().__init__(dimension, ind_domain=ind_domain, population_size=population_size, offspring=offspring,
mutation_sigma=mutation_sigma, embedding_size=latent_size, epochs=epochs,
batch_size=batch_size, learning_rate=learning_rate, seed=seed, device=device)
self._neighbors = _positive_int(neighbors, "neighbors")
self._additions = _positive_int(archive_additions, "archive_additions")
self._memory = deque(maxlen=_positive_int(novelty_capacity, "novelty_capacity"))
self._training_rows = deque(maxlen=_positive_int(training_capacity, "training_capacity"))
@property
def novelty_archive(self):
"""Return measured observations retained for latent novelty."""
return tuple(self._memory)
def _build_model(self):
return mc_aurora._EnsembleAutoencoder(self._shape, self._embedding_size).to(
device=self._device, dtype=self._torch.float32)
def _observation(self, observation):
values = super()._observation(observation)
if np.any(np.abs(values) > 1.):
raise ValueError("Scale autoencoder observations to [-1, 1].")
return values
def _model_scores(self, values):
batch = self._tensor(values)
with self._torch.no_grad():
latent = self._model.encoder(batch)
error = (self._model.decoder(latent) - batch).square().reshape(len(batch), -1).mean(dim=1)
return latent.cpu().numpy(), error.cpu().numpy()
## @brief Re-encode an observation using the current autoencoder.
[docs]
def encode(self, observation):
"""Return the current latent descriptor of one previously measurable observation."""
if self._model is None:
raise RuntimeError("Evaluate an observation before encoding.")
return tuple(self._model_scores(self._observation(observation)[None])[0][0].tolist())
def _latent_novelty(self, rows, reference):
if not reference:
return np.zeros(len(rows))
combined = list(dict.fromkeys((*rows, *reference)))
with self._torch.no_grad():
latent = self._model.encoder(self._tensor(np.stack([row.observation for row in combined]))).cpu().numpy()
indices = {row: i for i, row in enumerate(combined)}
sources = [indices[row] for row in rows]
targets = [indices[row] for row in reference]
return self._nearest(latent[sources], latent[targets], sources, targets)
def _nearest(self, source, target, source_ids, target_ids):
distances = cdist(source, target)
distances[np.equal.outer(source_ids, target_ids)] = np.inf
k = min(self._neighbors, len(target))
nearest = np.partition(distances, k - 1, axis=1)[:, :k]
available = np.isfinite(nearest)
return np.where(available, nearest, 0.).sum(axis=1) / np.maximum(1, available.sum(axis=1))
def _rank(self, scores):
return np.argsort(-scores[:, int(self._variation.integers(2))], kind="stable")
def _commit_exploration(self, children):
pool = self._population + children
reference = list(dict.fromkeys((*pool, *self._memory)))
latent, errors = self._model_scores(np.stack([row.observation for row in reference]))
novelty = self._nearest(latent[:len(pool)], latent, range(len(pool)), range(len(reference)))
scores = np.column_stack((novelty, errors[:len(pool)]))
start = len(self._population)
ranked = self._rank(scores)
survivors = [int(i) - start for i in ranked if i >= start]
self._memory.extend(children[i] for i in survivors[:self._additions])
self._population = [pool[i] for i in ranked[:self._population_size]]
self._training_rows.extend(children)
training = list(dict.fromkeys((*self._training_rows, *self._memory)))
self._fit(training, lambda batch: (self._model(batch) - batch).square().mean())
## @brief Alternate Pareto novelty/surprise exploration with local reward emitters.
[docs]
class STAX(TAXONS):
"""Learn behavior from observations while exploiting sparse reward discoveries.
A successful evaluation can seed an emitter with reward-only survival.
Promising bootstrap emitters continue on a novelty/improvement Pareto
front. Model refits reuse measured observations. The reward archive
stores observations and genomes independently of the current latent
coordinates.
:param dimension: Number of real parameters per genome.
:param reward_threshold: Seed and retain policies with reward strictly above this value.
:param emitter_budget: Maximum reward-search calls after each exploration generation.
:param emitter_sigma: Local mutation strength as a fraction of the genome span.
:param emitter_size: Maximum number of parents per emitter.
:param bootstrap_calls: Calls before accepting an improving emitter.
:param stagnation_calls: Nonimproving calls before retiring an active emitter.
:param max_emitters: Bound on each queue and the active emitter pool.
:param reward_capacity: Maximum retained reward records.
:param kwargs: TAXONS representation and exploration settings.
"""
def __init__(self, dimension, *, reward_threshold=0., emitter_budget=16, emitter_sigma=.03, emitter_size=4,
bootstrap_calls=4, stagnation_calls=20, max_emitters=8, reward_capacity=128, **kwargs):
super().__init__(dimension, **kwargs)
self._threshold, self._emitter_scale = reward_threshold, self._span * emitter_sigma
if not (np.isfinite(reward_threshold) and 0. < self._emitter_scale < np.inf):
raise ValueError("Use a finite threshold and finite positive emitter mutation scale.")
self._emitter_budget = _positive_int(emitter_budget, "emitter_budget")
self._emitter_size = _positive_int(emitter_size, "emitter_size")
self._bootstrap_calls = _positive_int(bootstrap_calls, "bootstrap_calls")
self._stagnation = _positive_int(stagnation_calls, "stagnation_calls")
self._limit = _positive_int(max_emitters, "max_emitters")
self._reward = deque(maxlen=_positive_int(reward_capacity, "reward_capacity"))
self._queued, self._active, self._probe = deque(maxlen=self._limit), [], None
self._remaining, self._boot_remaining = 0, 0
@property
def reward_archive(self):
"""Return the bounded reward archive in measurement order."""
return tuple(self._reward)
def _rank(self, scores):
return _nsga_order(scores, len(scores))[0]
def _commit_exploration(self, children):
super()._commit_exploration(children)
for row in children:
if row.reward > self._threshold:
self._queued.append(row)
self._reward.append(row)
if self._queued or self._probe is not None or self._active:
self._remaining = self._emitter_budget
self._boot_remaining = max(1, self._emitter_budget // 3)
def _measure(self, evaluate, parent, sigma, counter):
row = super()._measure(evaluate, parent, sigma, counter)
if row is not None and row.reward > self._threshold and self._first_reward is None:
self._first_reward = self.stats.evaluations
return row
def _select_emitter(self):
if (self._queued or self._probe is not None) and (self._boot_remaining or not self._active):
if self._probe is None:
index = int(np.argmax(self._latent_novelty(list(self._queued), self._reward)))
self._probe = _Emitter([self._queued[index]], 0.)
del self._queued[index]
self._counts["emitters_started"] += 1
self._boot_remaining = max(0, self._boot_remaining - 1)
return self._probe
reference = tuple(dict.fromkeys((*self._population, *self._memory)))
novelty = self._latent_novelty([emitter.population[0] for emitter in self._active], reference)
scores = np.column_stack((novelty, [emitter.improvement for emitter in self._active]))
return self._active[int(self._variation.choice(next(_pareto_fronts(scores))))]
def _advance(self, evaluate):
if not self._remaining or not (self._queued or self._probe is not None or self._active):
self._remaining = 0
self._explore(evaluate)
return
emitter = self._select_emitter()
probing = emitter is self._probe
best = emitter.population[0]
parent = emitter.population[int(self._variation.integers(len(emitter.population)))]
row = self._measure(evaluate, parent, self._emitter_scale,
"bootstrap_evaluations" if probing else "emitter_evaluations")
gain = 0.
if row is not None:
emitter.population.append(row)
emitter.population.sort(key=lambda item: item.reward, reverse=True)
del emitter.population[self._emitter_size:]
if row.reward > best.reward:
gain = row.reward - best.reward
self._reward.append(row)
reference = tuple(dict.fromkeys((*self._population, *self._memory)))
old, new = self._latent_novelty((best, row), reference)
if new > old:
self._memory.append(row)
if probing:
emitter.improvement += gain
emitter.probes += 1
if emitter.probes == self._bootstrap_calls:
if emitter.improvement > 0.:
if len(self._active) == self._limit:
weakest = min(range(len(self._active)), key=lambda i: self._active[i].improvement)
self._active.pop(weakest)
self._active.append(emitter)
self._probe = None
else:
emitter.improvement = .9 * emitter.improvement + .1 * gain
emitter.stalls = 0 if gain else emitter.stalls + 1
if emitter.stalls == self._stagnation:
self._active.remove(emitter)
self._remaining -= 1
## @brief Explore through prediction error against a frozen random behavior embedding.
[docs]
class BRNS(_ObservationSearch):
"""Run archive-free Behavior Recognition Novelty Search.
Score candidates with squared embedding prediction error before
training on the generation's newly measured observations. Use a
slightly deeper predictor with leaky ReLU and a linear output layer.
The retained population and the unfinished generation bound memory.
:param dimension: Number of real parameters per genome.
:param ind_domain: Common inclusive genome bounds.
:param population_size: Maximum breeding population.
:param offspring: Candidate evaluations in subsequent generations.
:param mutation_sigma: Gaussian strength as a fraction of the bounds' span.
:param embedding_size: Width of the fixed random embedding.
:param hidden_size: Width of the target and predictor hidden layers.
:param epochs: Prediction training epochs per generation.
:param batch_size: Maximum observations per optimization step.
:param learning_rate: Adam learning rate.
:param seed: Private rollout, variation and training seed.
:param device: PyTorch device.
"""
def __init__(self, dimension, *, ind_domain=(0., 1.), population_size=16, offspring=16, mutation_sigma=.12,
embedding_size=32, hidden_size=64, epochs=2, batch_size=32, learning_rate=1e-3,
seed=0, device="cpu"):
super().__init__(dimension, ind_domain=ind_domain, population_size=population_size, offspring=offspring,
mutation_sigma=mutation_sigma, embedding_size=embedding_size, epochs=epochs,
batch_size=batch_size, learning_rate=learning_rate, seed=seed, device=device)
self._hidden = _positive_int(hidden_size, "hidden_size")
self._target = None
def _build_model(self):
nn = self._torch.nn
width = prod(self._shape)
hidden = self._hidden
self._target = nn.Sequential(
nn.Flatten(), nn.Linear(width, hidden), nn.LeakyReLU(), nn.Linear(hidden, self._embedding_size)
).to(device=self._device, dtype=self._torch.float32).requires_grad_(False)
return nn.Sequential(nn.Flatten(), nn.Linear(width, hidden), nn.LeakyReLU(),
nn.Linear(hidden, hidden), nn.LeakyReLU(),
nn.Linear(hidden, self._embedding_size)).to(device=self._device, dtype=self._torch.float32)
def _scores(self, points):
return (self._model(points) - self._target(points)).square().sum(dim=1)
## @brief Score one observation using the current behavior recognizer.
[docs]
def novelty(self, observation):
"""Return squared prediction error for the observation."""
if self._model is None:
raise RuntimeError("Evaluate an observation before scoring novelty.")
with self._torch.no_grad():
return float(self._scores(self._tensor(self._observation(observation)[None]))[0])
def _commit_exploration(self, children):
pool = self._population + children
with self._torch.no_grad():
scores = self._scores(self._tensor(np.stack([row.observation for row in pool]))).cpu().numpy()
chosen = np.argsort(-scores, kind="stable")[:self._population_size]
self._population = [pool[i] for i in chosen]
self._fit(children, lambda batch: self._scores(batch).mean())