QDpy
Loading...
Searching...
No Matches
learned_exploration.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
7
8"""Run TAXONS, STAX, or BR-NS with bounded observation memory."""
9
10from collections import Counter, deque
11from dataclasses import dataclass
12from math import prod
13
14import numpy as np
15from scipy.spatial.distance import cdist
16
17from qdpy.containers import mc_aurora
18from ._population import _attempt_budget, _nsga_order, _pareto_fronts
19from .modern import _bounds, _positive_int
20from .serene import _Emitter
21
22__all__ = ["BRNS", "LearnedBehavior", "LearnedExplorationStats", "STAX", "TAXONS"]
23
24
25
26@dataclass(frozen=True, eq=False)
28 """Keep the numeric genome, reward, and a read-only observation array."""
29
30 genome: tuple[float, ...]
31 reward: float
32 observation: np.ndarray
33
34
35
36@dataclass(frozen=True)
38 """Candidate attempts include failures and prefixes of pending generations."""
39
40 exploration_evaluations: int = 0
41 bootstrap_evaluations: int = 0
42 emitter_evaluations: int = 0
43 failed_evaluations: int = 0
44 model_updates: int = 0
45 generations: int = 0
46 emitters_started: int = 0
47 first_reward_evaluation: int | None = None
48
49 @property
50 def evaluations(self):
51 """Return the total number of evaluator calls."""
53
54
56 """Measure and commit complete seeded generations with optional observations."""
57
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
63 self._device = self._torch.device(device)
64 self._dimension = _positive_int(dimension, "dimension")
65 self._population_size = _positive_int(population_size, "population_size")
66 self._offspring = _positive_int(offspring, "offspring")
67 self._epochs = _positive_int(epochs, "epochs")
68 self._batch_size = _positive_int(batch_size, "batch_size")
69 self._embedding_size = _positive_int(embedding_size, "embedding_size")
70 self._bounds = _bounds(ind_domain)
71 self._span = self._bounds[1] - self._bounds[0]
72 self._scale = self._span * mutation_sigma
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
76 self._variation, self._rollouts, self._training = map(
77 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
78 self._shape, self._model, self._optimizer = None, None, None
79 self._population, self._pending = [], []
80 self._pending_calls = 0
81 self._counts = Counter()
82 self._first_reward = None
83
84 @property
85 def population(self):
86 """Return the most recent committed exploration population."""
87 return tuple(self._population)
88
89 @property
90 def stats(self):
91 """Return cumulative search costs and completed generations."""
92 return LearnedExplorationStats(**self._counts, first_reward_evaluation=self._first_reward)
93
94 def _initialize_model(self):
95 torch = self._torch
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()
99 self._optimizer = torch.optim.Adam(self._model.parameters(), lr=self._rate)
100
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.")
106 return values
107
108 def _tensor(self, observations):
109 return self._torch.as_tensor(observations, device=self._device, dtype=self._torch.float32)
110
111 def _measure(self, evaluate, parent, sigma, counter):
112 if parent is None:
113 point = self._variation.uniform(*self._bounds, size=self._dimension)
114 else:
115 point = np.clip(np.asarray(parent.genome) + self._variation.normal(0., sigma, self._dimension),
116 *self._bounds)
117 genome = tuple(point.tolist())
118 self._counts[counter] += 1
119 result = evaluate(genome, int(self._rollouts.integers(2**32)))
120 if result is None:
121 self._counts["failed_evaluations"] += 1
122 return None
123 reward, observation = result
124 reward = float(reward)
125 if not np.isfinite(reward):
126 raise ValueError("Return a finite scalar reward.")
127 values = self._observation(observation)
128 values.setflags(write=False)
129 if self._model is None:
130 self._shape = values.shape
131 self._initialize_model()
132 return LearnedBehavior(genome, reward, values)
133
134 def _fit(self, records, objective):
135 if not records:
136 return
137 points = self._tensor(np.stack([row.observation for row in records]))
138 with self._torch.enable_grad():
139 for _ in range(self._epochs):
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.")
145 self._optimizer.zero_grad()
146 loss.backward()
147 self._optimizer.step()
148 self._counts["model_updates"] += 1
149
150 def _explore(self, evaluate):
151 parent = self._population[int(self._variation.integers(len(self._population)))] if self._population else None
152 row = self._measure(evaluate, parent, self._scale, "exploration_evaluations")
153 if row is not None:
154 self._pending.append(row)
155 self._pending_calls += 1
156 generation_size = self._offspring if self._population else self._population_size
157 if self._pending_calls < generation_size:
158 return False
159 if self._pending:
160 self._commit_exploration(self._pending)
161 self._pending, self._pending_calls = [], 0
162 self._counts["generations"] += 1
163 return True
164
165 def _advance(self, evaluate):
166 self._explore(evaluate)
167
168
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)):
177 self._advance(evaluate)
178 return self.stats
179
180
181
183 """Use latent k-nearest-neighbor novelty and reconstruction error.
184
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.
188
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.
204 """
205
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"))
216
217 @property
219 """Return measured observations retained for latent novelty."""
220 return tuple(self._memory)
221
222 def _build_model(self):
224 device=self._device, dtype=self._torch.float32)
225
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].")
230 return values
231
232 def _model_scores(self, values):
233 batch = self._tensor(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()
238
239
240 def encode(self, observation):
241 """Return the current latent descriptor of one previously measurable observation."""
242 if self._model is None:
243 raise RuntimeError("Evaluate an observation before encoding.")
244 return tuple(self._model_scores(self._observation(observation)[None])[0][0].tolist())
245
246 def _latent_novelty(self, rows, reference):
247 if not 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)
256
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
260 k = min(self._neighbors, len(target))
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))
264
265 def _rank(self, scores):
266 return np.argsort(-scores[:, int(self._variation.integers(2))], kind="stable")
267
268 def _commit_exploration(self, children):
269 pool = self._population + 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)]))
274 start = len(self._population)
275 ranked = self._rank(scores)
276 survivors = [int(i) - start for i in ranked if i >= start]
277 self._memory.extend(children[i] for i in survivors[:self._additions])
278 self._population = [pool[i] for i in ranked[:self._population_size]]
279 self._training_rows.extend(children)
280 training = list(dict.fromkeys((*self._training_rows, *self._memory)))
281 self._fit(training, lambda batch: (self._model(batch) - batch).square().mean())
282
283
285 """Learn behavior from observations while exploiting sparse reward discoveries.
286
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
291 coordinates.
292
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.
303 """
304
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)
308 self._threshold, self._emitter_scale = reward_threshold, self._span * emitter_sigma
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.")
311 self._emitter_budget = _positive_int(emitter_budget, "emitter_budget")
312 self._emitter_size = _positive_int(emitter_size, "emitter_size")
313 self._bootstrap_calls = _positive_int(bootstrap_calls, "bootstrap_calls")
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"))
317 self._queued, self._active, self._probe = deque(maxlen=self._limit), [], None
318 self._remaining, self._boot_remaining = 0, 0
319
320 @property
321 def reward_archive(self):
322 """Return the bounded reward archive in measurement order."""
323 return tuple(self._reward)
324
325 def _rank(self, scores):
326 return _nsga_order(scores, len(scores))[0]
327
328 def _commit_exploration(self, children):
329 super()._commit_exploration(children)
330 for row in children:
331 if row.reward > self._threshold:
332 self._queued.append(row)
333 self._reward.append(row)
334 if self._queued or self._probe is not None or self._active:
335 self._remaining = self._emitter_budget
336 self._boot_remaining = max(1, self._emitter_budget // 3)
337
338 def _measure(self, evaluate, parent, sigma, counter):
339 row = super()._measure(evaluate, parent, sigma, counter)
340 if row is not None and row.reward > self._threshold and self._first_reward is None:
341 self._first_reward = self.stats.evaluations
342 return row
343
344 def _select_emitter(self):
345 if (self._queued or self._probe is not None) and (self._boot_remaining or not self._active):
346 if self._probe is None:
347 index = int(np.argmax(self._latent_novelty(list(self._queued), self._reward)))
348 self._probe = _Emitter([self._queued[index]], 0.)
349 del self._queued[index]
350 self._counts["emitters_started"] += 1
351 self._boot_remaining = max(0, self._boot_remaining - 1)
352 return self._probe
353 reference = tuple(dict.fromkeys((*self._population, *self._memory)))
354 novelty = self._latent_novelty([emitter.population[0] for emitter in self._active], reference)
355 scores = np.column_stack((novelty, [emitter.improvement for emitter in self._active]))
356 return self._active[int(self._variation.choice(next(_pareto_fronts(scores))))]
357
358 def _advance(self, evaluate):
359 if not self._remaining or not (self._queued or self._probe is not None or self._active):
360 self._remaining = 0
361 self._explore(evaluate)
362 return
363 emitter = self._select_emitter()
364 probing = emitter is self._probe
365 best = emitter.population[0]
366 parent = emitter.population[int(self._variation.integers(len(emitter.population)))]
367 row = self._measure(evaluate, parent, self._emitter_scale,
368 "bootstrap_evaluations" if probing else "emitter_evaluations")
369 gain = 0.
370 if row is not None:
371 emitter.population.append(row)
372 emitter.population.sort(key=lambda item: item.reward, reverse=True)
373 del emitter.population[self._emitter_size:]
374 if row.reward > best.reward:
375 gain = row.reward - best.reward
376 self._reward.append(row)
377 reference = tuple(dict.fromkeys((*self._population, *self._memory)))
378 old, new = self._latent_novelty((best, row), reference)
379 if new > old:
380 self._memory.append(row)
381 if probing:
382 emitter.improvement += gain
383 emitter.probes += 1
384 if emitter.probes == self._bootstrap_calls:
385 if emitter.improvement > 0.:
386 if len(self._active) == self._limit:
387 weakest = min(range(len(self._active)), key=lambda i: self._active[i].improvement)
388 self._active.pop(weakest)
389 self._active.append(emitter)
390 self._probe = None
391 else:
392 emitter.improvement = .9 * emitter.improvement + .1 * gain
393 emitter.stalls = 0 if gain else emitter.stalls + 1
394 if emitter.stalls == self._stagnation:
395 self._active.remove(emitter)
396 self._remaining -= 1
397
398
399
401 """Run archive-free Behavior Recognition Novelty Search.
402
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.
407
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.
420 """
421
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")
429 self._target = None
430
431 def _build_model(self):
432 nn = self._torch.nn
433 width = prod(self._shape)
434 hidden = self._hidden
435 self._target = nn.Sequential(
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(),
440 nn.Linear(hidden, self._embedding_size)).to(device=self._device, dtype=self._torch.float32)
441
442 def _scores(self, points):
443 return (self._model(points) - self._target(points)).square().sum(dim=1)
444
445
446 def novelty(self, observation):
447 """Return squared prediction error for the observation."""
448 if self._model is None:
449 raise RuntimeError("Evaluate an observation before scoring novelty.")
450 with self._torch.no_grad():
451 return float(self._scores(self._tensor(self._observation(observation)[None]))[0])
452
453 def _commit_exploration(self, children):
454 pool = self._population + children
455 with self._torch.no_grad():
456 scores = self._scores(self._tensor(np.stack([row.observation for row in pool]))).cpu().numpy()
457 chosen = np.argsort(-scores, kind="stable")[:self._population_size]
458 self._population = [pool[i] for i in chosen]
459 self._fit(children, lambda batch: self._scores(batch).mean())
Explore through prediction error against a frozen random behavior embedding.
novelty(self, observation)
Score one observation using the current behavior recognizer.
One measured candidate with its unchanged observation.
Count exploration, reward exploitation and model fitting separately.
Alternate Pareto novelty/surprise exploration with local reward emitters.
Learn an outcome space with an autoencoder and explore by novelty or surprise.
encode(self, observation)
Re-encode an observation using the current autoencoder.
_nearest(self, source, target, source_ids, target_ids)
run(self, evaluate, budget)
Measure another hard budget while retaining partial generations.
Dense MC-AURORA default with a smooth activation in the hidden layers.
Definition mc_aurora.py:32