QDpy
Loading...
Searching...
No Matches
pbt.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""SAC-based PBT-MAP-Elites with bounded synchronous environment interaction."""
6
7from dataclasses import dataclass, replace
8from math import prod
9
10import numpy as np
11import torch
12from torch.nn.utils import parameters_to_vector
13
14from qdpy.tools import iso_line_dd
15from .policy import _integer
16from .rollout import TrainingStats, _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
17from .sac import SACConfig, SACPolicy, _SACLearner
18from .search import NeuralMAPElites
19
20
21
22@dataclass(frozen=True)
24 """Report warm-up and evolutionary work alongside SAC optimizer updates."""
25
26 generations: int = 0
27 population_replacements: int = 0
28 archive_replacements: int = 0
29 genetic_offspring: int = 0
30 actor_updates: int = 0
31 critic_updates: int = 0
32 temperature_updates: int = 0
33
34
35@dataclass(frozen=True)
37 """Copy the learned policy, critics, target critics, and temperature by value."""
38
39 vector: np.ndarray
40 config: SACConfig
41
42 @staticmethod
43 def _parameters(learner):
44 return (*learner.actor._trainable_parameters(), *learner.critics.parameters(),
45 *learner.critic_targets.parameters(), learner.log_temperature)
46
47 @classmethod
48 @torch.no_grad()
49 def capture(cls, learner):
50 vector = parameters_to_vector(cls._parameters(learner)).cpu().numpy().copy()
51 vector.setflags(write=False)
52 return cls(vector, learner.config)
53
54 @torch.no_grad()
55 def install(self, learner, config):
56 vector = np.asarray(self.vector, dtype=np.float32)
57 if not np.isfinite(vector).all():
58 raise ValueError("All transferred SAC parameters must be representable in float32.")
59 values = learner.actor._tensor(vector.copy())
60 offset = 0
61 for parameter in self._parameters(learner):
62 stop = offset + parameter.numel()
63 parameter.copy_(values[offset:stop].view_as(parameter))
64 offset = stop
65 # A variation or donor transfer starts fresh Adam moments. Replay,
66 # environment steps, and random streams belong to each population slot.
67 optimizers = ((learner.actor_optimizer, config.actor_learning_rate),
68 (learner.critic_optimizer, config.critic_learning_rate),
69 (learner.temperature_optimizer, config.temperature_learning_rate))
70 for optimizer, rate in optimizers:
71 optimizer.state.clear()
72 for group in optimizer.param_groups:
73 group["lr"] = rate
74 learner.config = config
75 entropy = config.target_entropy
76 learner.target_entropy = -prod(learner.actor._actions.shape) if entropy is None else entropy
77
78
79
81 """Population-Based Training MAP-Elites following Pierrot and Flajolet (ICLR 2023).
82
83 Each population slot owns a SAC learner, replay buffer, and random
84 streams. After measuring the initial population, each generation
85 replaces low-ranked agents with top-ranked donors, injects agents
86 from the archive into middle ranks, and trains each slot separately.
87 Iso+LineDD offspring combine complete trainable agent states.
88 Replay holds only exploratory training transitions.
89
90 :param env_factory: Factory for a continuous Box Gymnasium environment.
91 :param archive: Empty one-elite Grid or CVTGrid for measured policies.
92 :param descriptor: Episodic descriptor callback as in NeuralMAPElites.
93 :param sac: Base SACConfig used for each agent.
94 :param hyperparameter_ranges: Optional mapping of SAC field names to
95 inclusive (min, max) mutation ranges. Supports actor, critic and
96 temperature learning rates, gamma, tau, and target_entropy.
97 Omit to vary the actor and critic learning rates by factors of
98 0.5 through 2. An empty mapping disables hyperparameter resampling.
99 :param population_size: Number of independent SAC agents.
100 :param elite_count: Number of top-ranked eligible population donors.
101 :param exploit_count: Number of lowest-ranked slots replaced from donors.
102 :param archive_replacements: Number of middle-ranked slots replaced from archive elites.
103 :param training_steps_per_agent: Environment training steps per agent per generation.
104 :param offspring: Number of additionally scored genetic offspring per generation.
105 :param kwargs: Native policy architecture, episode, mutation, and seed settings.
106 """
107
108 _mutable_fields = frozenset(("actor_learning_rate", "critic_learning_rate", "temperature_learning_rate",
109 "gamma", "tau", "target_entropy"))
110
111 def __init__(self, env_factory, archive, *, descriptor, sac=None, hyperparameter_ranges=None,
112 population_size=6, elite_count=1, exploit_count=1, archive_replacements=2,
113 training_steps_per_agent=128, offspring=2, **kwargs):
114 self._config = SACConfig() if sac is None else sac
115 if not isinstance(self._config, SACConfig):
116 raise TypeError("sac must be a SACConfig.")
117 self._size = _integer(population_size, "population_size", 2)
118 self._elite_count = _integer(elite_count, "elite_count")
119 self._exploit_count = _integer(exploit_count, "exploit_count", 0)
120 self._archive_replacements = _integer(archive_replacements, "archive_replacements", 0)
121 if self._elite_count + self._exploit_count + self._archive_replacements > self._size:
122 raise ValueError("Elite, exploit, and archive replacement groups must fit the population.")
123 self._training_steps = _integer(training_steps_per_agent, "training_steps_per_agent")
124 self._offspring = _integer(offspring, "offspring", 0)
125 if hyperparameter_ranges is None:
126 hyperparameter_ranges = {name: (getattr(self._config, name) / 2, 2 * getattr(self._config, name))
127 for name in ("actor_learning_rate", "critic_learning_rate")}
128 self._ranges = {}
129 for name, (low, high) in sorted(hyperparameter_ranges.items()):
130 if name not in self._mutable_fields or low is None or high is None or low > high:
131 raise ValueError(f"Invalid SAC hyperparameter range for {name!r}.")
132 replace(self._config, **{name: low})
133 replace(self._config, **{name: high})
134 if not np.isfinite(high - low):
135 raise ValueError(f"Use finite numeric bounds for {name!r}.")
136 self._ranges[name] = (low, high)
137 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
138 self._population = [_SACLearner(self._new_actor(_seed(self._actor_rng)), self._resample(self._config),
139 _seed(self._training_rng), self._counts) for _ in range(self._size)]
140 self._steps = [0] * self._size
141 self._reset_rngs = [np.random.default_rng(_seed(self._training_rng)) for _ in self._population]
142 self._exploration_rngs = [np.random.default_rng(_seed(self._training_rng)) for _ in self._population]
143 self._archive_states = {}
144 self._fitnesses = None
145
146 def _build_actor(self, env, config, seed, device):
147 return SACPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
148
149 def _resample(self, config):
150 updates = {name: self._selection_rng.uniform(low, high) for name, (low, high) in self._ranges.items()}
151 return replace(config, **updates)
152
153 @property
154 def stats(self):
155 """Return cumulative environment steps and population activity."""
156 return PBTStats(**self._counts)
157
158 @property
160 """Return the current frozen SACConfig of each population slot."""
161 return tuple(learner.config for learner in self._population)
162
163 @property
165 """Return the worst-case cost of scoring the initial population and offspring."""
166 return (self._size + self._offspring) * self._episodes * self._horizon
167
168 @property
170 """Return the worst-case cost of a complete train-and-score generation."""
171 return self.initialization_step_limit + self._size * self._training_steps
172
173 def _repertoire_states(self):
174 return [state for cell, (elite, state) in self._archive_states.items()
175 if self.archive.solutions[cell] and self.archive.solutions[cell][0] is elite]
176
177 def _replace_population(self):
178 ranked = np.argsort(-self._fitnesses, kind="stable")
179 donors = [_AgentState.capture(self._population[i]) for i in ranked[:self._elite_count]]
180 if self._exploit_count:
181 for slot in ranked[-self._exploit_count:]:
182 state = donors[self._selection_rng.integers(len(donors))]
183 state.install(self._population[slot], self._resample(state.config))
184 self._counts["population_replacements"] += 1
185 repertoire = self._repertoire_states()
186 if repertoire and self._archive_replacements:
187 middle = ranked[self._elite_count:self._size - self._exploit_count]
188 for slot in self._selection_rng.choice(middle, self._archive_replacements, replace=False):
189 state = repertoire[self._selection_rng.integers(len(repertoire))]
190 state.install(self._population[slot], self._resample(state.config))
191 self._counts["archive_replacements"] += 1
192
193 def _train_agents(self, env, budget):
194 for slot, learner in enumerate(self._population):
195 cursor = _Cursor(env, learner.actor, self._horizon, self._reset_rngs[slot])
196 for _ in range(self._training_steps):
197 if cursor.ended:
198 cursor.reset()
199 obs = cursor.observation
200 if self._steps[slot] < learner.config.learning_starts:
201 action = learner.actor._decode(self._exploration_rngs[slot].uniform(
202 -1, 1, prod(learner.actor._actions.shape)))
203 else:
204 action = learner.actor._draw(obs, False, learner.actor._rng)[0]
205 saved_action = action.copy()
206 reward, terminated, _, _ = cursor.step(action, budget, "training_steps")
207 learner.record(obs, saved_action, reward, cursor.observation, terminated)
208 self._steps[slot] += 1
209 if learner.ready(self._steps[slot]):
210 learner.update()
211
212 def _score(self, cursor, budget, state, emitter):
213 actor_size = sum(parameter.numel() for parameter in self._actor._trainable_parameters())
214 self._actor._set_parameters(state.vector[:actor_size])
215 self._counts["candidate_attempts"] += 1
216 episodes = [_evaluate_episode(cursor, self._actor, budget) for _ in range(self._episodes)]
217 quality = float(np.mean([episode.return_ if self._fitness is None else self._fitness(episode)
218 for episode in episodes]))
219 self._counts["evaluated_policies"] += 1
220 elite = self._offer(episodes, emitter, quality=quality)
221 if elite is not None:
222 self._archive_states[self.archive.index_grid(elite)] = elite, state
223 if self._on_step is not None:
224 self._on_step(self.archive, self.stats)
225 return quality
226
227 def _report_population(self, cursor, budget):
228 population = [_AgentState.capture(learner) for learner in self._population]
229 self._fitnesses = np.asarray([self._score(cursor, budget, state, "pbt") for state in population])
230 for _ in range(self._offspring):
231 entries = self._repertoire_states() or population
232 first, second = (entries[i] for i in self._selection_rng.integers(len(entries), size=2))
233 vector = iso_line_dd(first.vector, second.vector, iso_sigma=self._iso_sigma,
234 line_sigma=self._line_sigma, rng=self._selection_rng)
235 # The last coordinate is log temperature. Keep its exponential representable.
236 vector[-1] = np.clip(vector[-1], -80., 80.)
237 if np.any(~np.isfinite(vector)) or np.any(np.abs(vector) > np.finfo(np.float32).max):
238 raise ValueError("Genetic variation produced unrepresentable SAC weights.")
239 vector.setflags(write=False)
240 self._counts["genetic_offspring"] += 1
241 self._score(cursor, budget, _AgentState(vector, first.config), "pbt-genetic")
242
243
244 def train(self, max_env_steps):
245 """Return cumulative statistics. Unspent steps are local to this call."""
246 budget = _StepBudget(max_env_steps, self._counts)
247 minimum = self.initialization_step_limit if self._fitnesses is None else self.generation_step_limit
248 if budget.remaining >= minimum:
249 with _open_environment(self._factory) as env:
250 _check_spaces(env, self._actor)
251 evaluation = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
252 if self._fitnesses is None:
253 self._report_population(evaluation, budget)
254 while budget.remaining >= self.generation_step_limit:
256 self._train_agents(env, budget)
257 self._report_population(evaluation, budget)
258 self._counts["generations"] += 1
259 return self.stats
Alternate independent SAC training, population replacement, and archive variation.
Definition pbt.py:80
_train_agents(self, env, budget)
Definition pbt.py:193
initialization_step_limit(self)
Definition pbt.py:164
_score(self, cursor, budget, state, emitter)
Definition pbt.py:212
_resample(self, config)
Definition pbt.py:149
train(self, max_env_steps)
Train whole population generations within a hard additional step budget.
Definition pbt.py:244
_report_population(self, cursor, budget)
Definition pbt.py:227
generation_step_limit(self)
Definition pbt.py:169
_replace_population(self)
Definition pbt.py:177
Report environment budgets, learning updates, and sources of replacement agents.
Definition pbt.py:23
_parameters(learner)
Definition pbt.py:43
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Definition sac.py:23
Portable bounded Gaussian actor with an observation-dependent mean and scale.
Definition sac.py:88
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Definition search.py:24
_offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None)
Definition search.py:119
_new_actor(self, seed, device=None)
Definition search.py:112