38 """Use PGA proposals alongside periodic AURORA autoencoder fitting.
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.
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.
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.")
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.")
80 super().__init__(env_factory, archive, descriptor=self.
_rollout_trace,
81 initial_policies=initial_policies, seed=seed, **kwargs)
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)
90 def _rollout_trace(self, 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")
97 def _prepare(self, cursor, budget):
99 return super()._prepare(cursor, budget)
100 return NeuralMAPElites._prepare(self, cursor, budget)
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])
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
115 """Report environment, TD3 and autoencoder work."""
118 encoder_refits=encoder.refits, encoder_updates=encoder.optimizer_steps,
119 novelty_radius=encoder.novelty_radius)
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)
128 def _elite_count(self, count):
129 return min(count - 1, round(count * self.
fraction))
if self.
elites.size
else 0
131 def sample(self, count, rng, device):
133 shared = super().sample(count - elite_count, rng, device)
136 elite = self.
elites.sample(elite_count, rng, device)
137 return tuple(torch.cat((left, right))
for left, right
in zip(shared, elite))
139 def sample_observations(self, count, rng, device):
141 shared = super().sample_observations(count - elite_count, rng, device)
144 return torch.cat((shared, self.
elites.sample_observations(elite_count, rng, device)))
159 """Combine coordinate crossover, independent elite replay, and UCB1 allocation.
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.
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.
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)
192 prod(actor._actions.shape), elite_fraction)
194 def _genetic_parameters(self):
195 child = super()._genetic_parameters()
197 donor = np.asarray(self.
_parent())
199 child = np.where(mask, donor, child)
202 def _prepare(self, cursor, budget):
205 return super()._prepare(cursor, budget)
207 def _build_generation(self):
209 return super()._build_generation()
214 total = sum(arm.draws
for arm
in self.
_arms)
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())))
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"]
230 arm.successes += admitted
is not None
232 if admitted
is not None and isinstance(replay, _EliteReplay):
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)
241 """Report measured arm credit and both replay sizes."""
243 elite_size = replay.elites.size
if isinstance(replay, _EliteReplay)
else 0
245 operator_trials=tuple(arm.draws
for arm
in self.
_arms),
246 operator_successes=tuple(arm.successes
for arm
in self.
_arms))