37 """Copy the learned policy, critics, target critics, and temperature by value."""
43 def _parameters(learner):
44 return (*learner.actor._trainable_parameters(), *learner.critics.parameters(),
45 *learner.critic_targets.parameters(), learner.log_temperature)
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)
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())
62 stop = offset + parameter.numel()
63 parameter.copy_(values[offset:stop].view_as(parameter))
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:
74 learner.config = config
75 entropy = config.target_entropy
76 learner.target_entropy = -prod(learner.actor._actions.shape)
if entropy
is None else entropy
81 """Population-Based Training MAP-Elites following Pierrot and Flajolet (ICLR 2023).
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.
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.
108 _mutable_fields = frozenset((
"actor_learning_rate",
"critic_learning_rate",
"temperature_learning_rate",
109 "gamma",
"tau",
"target_entropy"))
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):
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")
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")}
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)
146 def _build_actor(self, env, config, seed, device):
147 return SACPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
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)
155 """Return cumulative environment steps and population activity."""
160 """Return the current frozen SACConfig of each population slot."""
161 return tuple(learner.config
for learner
in self.
_population)
165 """Return the worst-case cost of scoring the initial population and offspring."""
170 """Return the worst-case cost of a complete train-and-score generation."""
173 def _repertoire_states(self):
175 if self.
archive.solutions[cell]
and self.
archive.solutions[cell][0]
is elite]
177 def _replace_population(self):
178 ranked = np.argsort(-self.
_fitnesses, kind=
"stable")
184 self.
_counts[
"population_replacements"] += 1
191 self.
_counts[
"archive_replacements"] += 1
193 def _train_agents(self, env, budget):
199 obs = cursor.observation
200 if self.
_steps[slot] < learner.config.learning_starts:
202 -1, 1, prod(learner.actor._actions.shape)))
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)
209 if learner.ready(self.
_steps[slot]):
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:
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])
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,
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
245 """Return cumulative statistics. Unspent steps are local to this call."""
248 if budget.remaining >= minimum:
249 with _open_environment(self.
_factory)
as env:
250 _check_spaces(env, self.
_actor)
258 self.
_counts[
"generations"] += 1