QDpy
Loading...
Searching...
No Matches
adaptive_pga.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Combine PGA with AURORA or adaptive crossover and dual replay."""
8
9from dataclasses import dataclass
10from math import prod
11
12import numpy as np
13import torch
14
15from qdpy.algorithms.aurora_xcon import AuroraXCon, _AuroraRepertoire
16from qdpy.algorithms.monte_carlo import _Arm, _ucb
17
18from .pga import PGAMAPElites
19from .policy import _integer
20from .search import NeuralMAPElites
21from .td3 import OffPolicyStats, _Replay
22
23__all__ = ["PGAAURORA", "PGAAuroraStats", "AdaHOME", "AdaHOMEStats"]
24
25
26
27@dataclass(frozen=True)
29 """Encoder remaps do not count as fresh archive evaluations."""
30
31 encoder_refits: int = 0
32 encoder_updates: int = 0
33 novelty_radius: float = 0.
34
35
36
38 """Use PGA proposals alongside periodic AURORA autoencoder fitting.
39
40 Completed rollouts provide fitness and a fixed-size trajectory. The
41 autoencoder learns from the warmup candidates and later from retained
42 policies. Refits use cached trajectories and rebuild the repertoire.
43 Incomplete candidates can supply TD3 replay through the ordinary PGA
44 loop. They do not provide descriptors.
45
46 :param env_factory: Callable constructing a Gymnasium Box environment.
47 :param trajectory: Optional callable (episode) returning a rank-two
48 fixed-shape trajectory scaled to [-1, 1]. By default observations
49 are flattened, transformed by tanh and padded with the last row.
50 :param latent_size: Width of the latent descriptors.
51 :param capacity: Hard maximum number of retained policies.
52 :param radius: Initial novelty radius.
53 :param training_period: Completed policies between encoder refits.
54 :param encoder_epochs: Reconstruction passes per refit.
55 :param encoder_batch_size: Maximum trajectories in a reconstruction update.
56 :param size_gain: AURORA proportional size controller gain in [0, 1].
57 :param gradient: Enable the PGA schedule. False runs the genetic AURORA control.
58 :param initial_policies: Number of complete random policies for the first fit.
59 :param seed: Root variation, rollout and encoder seed.
60 :param kwargs: Other PGA-MAP-Elites policy, replay and evaluation settings.
61 """
62
63 @staticmethod
64 def _validate_archive(archive):
65 if type(archive) is not _AuroraRepertoire or archive:
66 raise ValueError("PGA-AURORA constructs its own empty unstructured archive.")
67
68 def __init__(self, env_factory, *, trajectory=None, latent_size=2, capacity=128, radius=.08,
69 training_period=32, encoder_epochs=4, encoder_batch_size=32, size_gain=.02,
70 gradient=True, initial_policies=8, seed=0, **kwargs):
71 if trajectory is not None and not callable(trajectory):
72 raise TypeError("trajectory must be callable.")
73 if type(gradient) is not bool:
74 raise TypeError("gradient must be a bool.")
75 latent_size, capacity = _integer(latent_size, "latent_size"), _integer(capacity, "capacity")
76 if not 0 < radius < np.inf:
77 raise ValueError("Use a finite positive novelty radius.")
78 self._trajectory, self._gradient = trajectory, gradient
79 archive = _AuroraRepertoire(latent_size, radius, capacity)
80 super().__init__(env_factory, archive, descriptor=self._rollout_trace,
81 initial_policies=initial_policies, seed=seed, **kwargs)
82 self._aurora = AuroraXCon(dimension=len(self._actor._parameters()), latent_size=latent_size, capacity=capacity,
83 radius=radius, initial_samples=self._initial_policies, training_period=training_period,
84 epochs=encoder_epochs, batch_size=encoder_batch_size, loss="reconstruction",
85 size_gain=size_gain, extinction_period=0, seed=seed, device=self._actor.device)
86 self.archive = self._aurora.archive
87 if not gradient:
88 self._transition = None
89
90 def _rollout_trace(self, episode):
91 if self._trajectory is not None:
92 return self._trajectory(episode)
93 observations = np.tanh(episode.observations.reshape(episode.steps + 1, -1))
94 padding = self._horizon - episode.steps
95 return np.pad(observations, ((0, padding), (0, 0)), mode="edge")
96
97 def _prepare(self, cursor, budget):
98 if self._gradient:
99 return super()._prepare(cursor, budget)
100 return NeuralMAPElites._prepare(self, cursor, budget)
101
102 def _offer(self, episodes, emitter):
103 trajectory = np.stack([self._rollout_trace(row) for row in episodes]).mean(axis=0)
104 fitness = np.mean([row.return_ if self._fitness is None else self._fitness(row) for row in episodes])
105 learner = self._aurora
106 before = learner._counts["archive_updates"]
107 learner._record(self._actor._parameters().tolist(), fitness, trajectory)
108 learner._counts["evaluations"] += 1
109 learner._refresh_representation()
110 self._counts["archive_updates"] += learner._counts["archive_updates"] - before
111 self.archive = learner.archive
112
113 @property
114 def stats(self):
115 """Report environment, TD3 and autoencoder work."""
116 encoder = self._aurora.stats
117 return PGAAuroraStats(**self._counts, replay_size=self._learner.replay.size,
118 encoder_refits=encoder.refits, encoder_updates=encoder.optimizer_steps,
119 novelty_radius=encoder.novelty_radius)
120
121
123 def __init__(self, capacity, elite_capacity, obs_width, action_width, fraction):
124 super().__init__(capacity, obs_width, action_width)
125 self.elites = _Replay(elite_capacity, obs_width, action_width)
126 self.fraction = fraction
127
128 def _elite_count(self, count):
129 return min(count - 1, round(count * self.fraction)) if self.elites.size else 0
130
131 def sample(self, count, rng, device):
132 elite_count = self._elite_count(count)
133 shared = super().sample(count - elite_count, rng, device)
134 if not elite_count:
135 return shared
136 elite = self.elites.sample(elite_count, rng, device)
137 return tuple(torch.cat((left, right)) for left, right in zip(shared, elite))
138
139 def sample_observations(self, count, rng, device):
140 elite_count = self._elite_count(count)
141 shared = super().sample_observations(count - elite_count, rng, device)
142 if not elite_count:
143 return shared
144 return torch.cat((shared, self.elites.sample_observations(elite_count, rng, device)))
145
146
147
148@dataclass(frozen=True)
150 """Operator counters are ordered genetic, then gradient."""
151
152 operator_trials: tuple[int, int] = (0, 0)
153 operator_successes: tuple[int, int] = (0, 0)
154 elite_replay_size: int = 0
155
156
157
159 """Combine coordinate crossover, independent elite replay, and UCB1 allocation.
160
161 Genetic offspring can copy whole weights from an archive donor after
162 Iso+LineDD. The replay ring retains all transitions and a second ring
163 retains full episodes from admitted candidates. TD3 and gradient
164 offspring sample from both. The two-arm bandit allocates the slots
165 alongside one evaluated greedy actor. Credit is applied only when
166 a scheduled proposal completes its rollout.
167
168 :param env_factory: Callable constructing a Gymnasium Box environment.
169 :param archive: Parentless native Grid or CVTGrid for measured descriptors.
170 :param adaptive: Enable bandit allocation instead of the fixed PGA ratio.
171 :param exploration: Nonnegative UCB1 exploration coefficient.
172 :param swap_probability: Chance of copying each weight from an archive donor.
173 :param elite_capacity: Maximum extra elite transitions retained.
174 :param elite_fraction: Fraction sampled from elite replay, in [0, 1).
175 :param kwargs: PGA-MAP-Elites evaluation, policy and optimizer settings.
176 """
177
178 def __init__(self, env_factory, archive, *, adaptive=True, exploration=1., swap_probability=.1,
179 elite_capacity=1024, elite_fraction=.25, **kwargs):
180 if type(adaptive) is not bool:
181 raise TypeError("adaptive must be a bool.")
182 if not (0 <= exploration < np.inf and 0 <= swap_probability <= 1. and 0 <= elite_fraction < 1.):
183 raise ValueError("Use valid exploration and replay or crossover probabilities.")
184 elite_capacity = _integer(elite_capacity, "elite_capacity")
185 super().__init__(env_factory, archive, **kwargs)
186 self._adaptive, self._exploration, self._swap = adaptive, exploration, swap_probability
187 self._arms = (_Arm(), _Arm())
188 self._credit = False
189 if elite_fraction:
190 actor = self._learner.actor
191 self._learner.replay = _EliteReplay(self.td3.replay_capacity, elite_capacity, prod(actor._obs_shape),
192 prod(actor._actions.shape), elite_fraction)
193
194 def _genetic_parameters(self):
195 child = super()._genetic_parameters()
196 if self._swap and self._can_select():
197 donor = np.asarray(self._parent())
198 mask = self._selection_rng.random(len(child)) < self._swap
199 child = np.where(mask, donor, child)
200 return child
201
202 def _prepare(self, cursor, budget):
203 self._credit = bool(self._generation or (
204 self._can_select() and self._learner.ready(self._counts["evaluation_steps"])))
205 return super()._prepare(cursor, budget)
206
207 def _build_generation(self):
208 if not self._adaptive:
209 return super()._build_generation()
210 for _ in range(self.critic_steps):
211 self._learner.update()
212 self._generation.append(("greedy", self._learner.actor._parameters()))
213 queued = [0, 0]
214 total = sum(arm.draws for arm in self._arms)
215 for slot in range(self.batch_size - 1):
216 scores = np.asarray([_ucb(_Arm(arm.draws + count, arm.successes), total + slot, self._exploration)
217 for arm, count in zip(self._arms, queued)])
218 index = int(self._selection_rng.choice(np.flatnonzero(scores == scores.max())))
219 queued[index] += 1
220 if index == 0:
221 self._generation.append(("genetic", self._genetic_parameters()))
222 else:
223 self._generation.append(("pg", self._gradient_parameters()))
224
225 def _offer(self, episodes, emitter):
226 admitted = super()._offer(episodes, emitter)
227 if self._credit and emitter in ("genetic", "pg"):
228 arm = self._arms[emitter == "pg"]
229 arm.draws += 1
230 arm.successes += admitted is not None
231 replay = self._learner.replay
232 if admitted is not None and isinstance(replay, _EliteReplay):
233 for row in episodes:
234 for i, (action, reward) in enumerate(zip(row.actions, row.rewards)):
235 replay.elites.add(row.observations[i].reshape(-1), self._actor._encode(action), reward,
236 row.observations[i + 1].reshape(-1), row.terminated and i == row.steps - 1)
237 return admitted
238
239 @property
240 def stats(self):
241 """Report measured arm credit and both replay sizes."""
242 replay = self._learner.replay
243 elite_size = replay.elites.size if isinstance(replay, _EliteReplay) else 0
244 return AdaHOMEStats(**self._counts, replay_size=replay.size, elite_replay_size=elite_size,
245 operator_trials=tuple(arm.draws for arm in self._arms),
246 operator_successes=tuple(arm.successes for arm in self._arms))
Search with learned trajectory coordinates and a periodically pruned repertoire.
Record completed and admitted bandit proposals and retained elite transitions.
Adapt genetic and TD3 branch allocation using completed archive admissions.
Illuminate an unstructured learned descriptor archive with TD3 variation.
TD3 search and a separate count of learned-descriptor fitting work.
Illuminate a Box-control archive using TD3 and the PGA-MAP-Elites schedule.
Definition pga.py:17
_gradient_parameters(self)
Definition pga.py:96
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76