25 """Search for high-return policies with different measured behaviour.
27 Random Torch initializations fill the initial archive. Later offspring
28 use Iso+LineDD without clipping network weights. All policies use the
29 same architecture, and the archive owns copies of their flat genomes.
31 :param env_factory: Callable returning a fresh Gymnasium environment.
32 :param archive: Empty, parentless, best-only Grid or CVTGrid with one
33 fitness objective. If set, its fitness weight must be positive.
34 :param descriptor: Map a completed :class:`Episode` to a descriptor vector.
35 :param fitness: Optional function of a completed episode. Defaults to return.
36 :param policy: Actor architecture as a :class:`PolicyConfig`.
37 :param evaluation_episodes: Average this many complete episodes per policy.
38 :param initial_policies: Number of evaluated random policies before variation.
39 :param iso_sigma: Independent Iso+LineDD noise scale.
40 :param line_sigma: Shared Iso+LineDD noise scale.
41 :param max_episode_steps: Per-episode safety horizon.
42 :param seed: Nonnegative seed for selection, initialization, and resets.
43 :param device: Torch CPU or CUDA device.
44 :param on_step: Optional callable receiving the archive and a frozen
45 snapshot of cumulative stats after each completed candidate evaluation.
48 _stochastic_box =
False
50 _state_descriptor =
None
53 def _validate_archive(archive):
54 if (type(archive)
not in (Grid, CVTGrid)
or len(archive)
or archive.parents
55 or archive.max_items_per_bin != 1
or archive.discard_random_on_bin_overload
56 or archive.fitness_domain
is None or len(archive.fitness_domain) != 1
57 or not len(archive.features_domain)
58 or len(archive.fitness_score_names)
or len(archive.features_score_names)):
59 raise ValueError(
"Supply an empty, parentless, best-only Grid or CVTGrid with one fitness "
60 "objective and direct fitness and descriptors.")
61 weights = archive.fitness_weights
62 if weights
is not None and (len(weights) != 1
or not isfinite(weights[0])
or weights[0] <= 0):
63 raise ValueError(
"The archive must maximize a single fitness objective.")
65 def __init__(self, env_factory, archive, *, descriptor, fitness=None, policy=None,
66 evaluation_episodes=1, initial_policies=8, iso_sigma=0.01, line_sigma=0.2,
67 max_episode_steps=300, seed=0, device="cpu", on_step=None):
69 if not callable(env_factory)
or not callable(descriptor):
70 raise TypeError(
"env_factory and descriptor must be callable.")
71 if fitness
is not None and not callable(fitness):
72 raise TypeError(
"fitness must be callable.")
73 if on_step
is not None and not callable(on_step):
74 raise TypeError(
"on_step must be callable.")
75 if not (0 <= iso_sigma < np.inf
and 0 <= line_sigma < np.inf):
76 raise ValueError(
"Iso+LineDD scales must be finite and nonnegative.")
80 self.
_episodes = _integer(evaluation_episodes,
"evaluation_episodes")
82 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
84 seeds = np.random.SeedSequence(_integer(seed,
"seed", 0)).spawn(4)
86 np.random.default_rng(stream)
for stream
in seeds
89 with _open_environment(env_factory)
as env:
92 def _build_actor(self, env, config, seed, device):
93 return _make_policy(env, config, seed, device, stochastic=self.
_stochastic_box)
97 """Return immutable cumulative step and candidate counts."""
100 def _can_select(self):
106 def _genetic_parameters(self):
112 def _new_actor(self, seed, device=None):
113 return self.
_actor._new(seed, device)
115 def _prepare(self, cursor, budget):
119 def _offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None):
122 fitness = float(np.mean([episode.return_
if self.
_fitness is None else float(self.
_fitness(episode))
123 for episode
in episodes]))
124 if descriptors
is None:
125 descriptors = [np.asarray(self.
_descriptor(episode), dtype=float)
for episode
in episodes]
126 dimension = len(self.
archive.features_domain)
127 if not isfinite(fitness)
or any(row.shape != (dimension,)
or not np.isfinite(row).all()
128 for row
in descriptors):
129 raise ValueError(f
"Expected finite scalar fitness and finite descriptors of length {dimension}.")
130 features = tuple(np.mean(descriptors, axis=0))
132 (fitness,), self.
archive.fitness_domain):
133 self.
_counts[
"out_of_domain"] += 1
135 cell = self.
archive.index_grid(features)
138 genome = self.
_actor._parameters()
if parameters
is None else parameters
139 identifier = self.
_counts[
"candidate_attempts"]
if candidate_id
is None else candidate_id
140 elite =
_CellIndividual(genome.tolist(), cell, name=f
"{emitter}-{identifier}",
141 fitness=
Fitness((fitness,), weights=(1.,)), features=
Features(features))
144 updates = self.
archive.nb_added - before
145 self.
_counts[
"archive_updates"] += updates
146 return elite
if updates
else None
153 def train(self, max_env_steps, *, evaluation_batch_size=1, budget_aware=False):
154 """Return cumulative stats. A budget-cut candidate cannot enter the archive.
156 The optional batch size groups proposals before feedback and
157 batches actor inference across independent local environments.
158 Only plain NeuralMAPElites supports this mode. Proposals in a
159 batch use the same archive state and complete feedback is applied
160 in proposal order. Step callbacks see the consumed steps for the
161 batch as its feedback is applied.
163 With ``budget_aware=True``, the width is a ceiling. Reduce it to
164 reserve the worst-case steps for every episode of each policy.
165 When the remaining budget cannot reserve one complete policy,
166 advance one policy at a time until the budget is spent.
168 width = _integer(evaluation_batch_size,
"evaluation_batch_size")
169 if type(budget_aware)
is not bool:
170 raise TypeError(
"budget_aware must be a bool.")
172 if type(self)
is not NeuralMAPElites:
173 raise ValueError(
"Batched evaluation is available for plain NeuralMAPElites.")
176 with _open_environment(self.
_factory)
as env:
177 _check_spaces(env, self.
_actor)
180 while budget.remaining:
181 self.
_counts[
"candidate_attempts"] += 1
182 emitter = self.
_prepare(training, budget)
189 episodes.append(episode)
192 self.
_counts[
"evaluated_policies"] += 1
193 self.
_offer(episodes, emitter)
198 def _train_batched(self, max_env_steps, width, budget_aware):
202 def affordable_width():
203 return min(width, max(1, budget.remaining // steps_per_policy))
205 with ExitStack()
as stack:
207 for _
in range(affordable_width()):
208 env = stack.enter_context(_open_environment(self.
_factory))
209 _check_spaces(env, self.
_actor)
211 while budget.remaining:
212 group = cursors[:affordable_width()]
214 first_id = self.
_counts[
"candidate_attempts"] + 1
215 self.
_counts[
"candidate_attempts"] += len(genomes)
217 for candidate_id, (genome, measurements)
in enumerate(zip(genomes, episodes), first_id):
219 self.
_counts[
"evaluated_policies"] += 1
220 self.
_offer(measurements,
"genetic", parameters=genome, candidate_id=candidate_id)
227 """Decode a candidate using this search's observation and action layout."""
229 actor._set_parameters(individual)
234 """Return an independent copy of the best policy, or raise on an empty archive."""
236 raise RuntimeError(
"The archive contains no evaluated policy.")
242 """Use a configurable mixture of genetic and PPO-improved offspring.
244 After initial evaluations, a PPO offspring copies a parent actor and
245 starts a fresh value network and optimizer. A single fresh collection
246 is followed by the configured PPO epochs. Its final actor is then
247 evaluated independently with the same scoring as genetic offspring.
249 :param env_factory: Callable returning a fresh Gymnasium environment.
250 :param archive: Native reporting archive as in :class:`NeuralMAPElites`.
251 :param ppo: Optional :class:`PPOConfig` for offspring improvement.
252 :param ppo_probability: Probability of selecting PPO for an eligible
253 offspring. A short remaining budget can require genetic variation.
254 :param kwargs: Evaluation, policy, and variation options for
255 :class:`NeuralMAPElites`.
258 _stochastic_box =
True
260 def __init__(self, env_factory, archive, *, ppo=None, ppo_probability=0.5, **kwargs):
262 if not isinstance(self.
ppo, PPOConfig):
263 raise TypeError(
"ppo must be a PPOConfig.")
264 if not 0 <= ppo_probability <= 1:
265 raise ValueError(
"ppo_probability must be in [0, 1].")
267 super().__init__(env_factory, archive, **kwargs)
269 def _prepare(self, cursor, budget):
275 return super()._prepare(cursor, budget)
280 learner.update(cursor, budget, training_limit)
281 self.
_counts[
"ppo_offspring"] += 1