QDpy
Loading...
Searching...
No Matches
search.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Synchronous policy search with native QDpy archives."""
6
7from collections import Counter
8from contextlib import ExitStack
9from math import isfinite
10
11import numpy as np
12
13from qdpy.containers import CVTGrid, Grid
14from qdpy.phenotype import Features, Fitness, _CellIndividual
15from qdpy.tools import iso_line_dd
16
17from ._batch_rollout import _evaluate_batch
18from .policy import _integer, _make_policy
19from .ppo import PPOConfig, _Learner
20from .rollout import TrainingStats, _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
21
22
23
25 """Search for high-return policies with different measured behaviour.
26
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.
30
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.
46 """
47
48 _stochastic_box = False
49 _transition = None
50 _state_descriptor = None
51
52 @staticmethod
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.")
64
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):
68 self._validate_archive(archive)
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.")
77 self.archive = archive
78 self._factory, self._descriptor, self._fitness = env_factory, descriptor, fitness
79 self._on_step = on_step
80 self._episodes = _integer(evaluation_episodes, "evaluation_episodes")
81 self._initial_policies = _integer(initial_policies, "initial_policies")
82 self._horizon = _integer(max_episode_steps, "max_episode_steps")
83 self._iso_sigma, self._line_sigma = iso_sigma, line_sigma
84 seeds = np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(4)
86 np.random.default_rng(stream) for stream in seeds
87 )
88 self._counts = Counter()
89 with _open_environment(env_factory) as env:
90 self._actor = self._build_actor(env, policy, _seed(self._actor_rng), device)
91
92 def _build_actor(self, env, config, seed, device):
93 return _make_policy(env, config, seed, device, stochastic=self._stochastic_box)
94
95 @property
96 def stats(self):
97 """Return immutable cumulative step and candidate counts."""
98 return TrainingStats(**self._counts)
99
100 def _can_select(self):
101 return self.archive and self._counts["evaluated_policies"] >= self._initial_policies
102
103 def _parent(self):
104 return self.archive[int(self._selection_rng.integers(len(self.archive)))]
105
106 def _genetic_parameters(self):
107 if not self._can_select():
108 return self._new_actor(_seed(self._actor_rng))._parameters()
109 return iso_line_dd(self._parent(), self._parent(), iso_sigma=self._iso_sigma,
110 line_sigma=self._line_sigma, rng=self._selection_rng)
111
112 def _new_actor(self, seed, device=None):
113 return self._actor._new(seed, device)
114
115 def _prepare(self, cursor, budget):
116 self._actor._set_parameters(self._genetic_parameters())
117 return "genetic"
118
119 def _offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None):
120 fitness = quality
121 if fitness is 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))
131 if not self.archive.in_bounds(features, self.archive.features_domain) or not self.archive.in_bounds(
132 (fitness,), self.archive.fitness_domain):
133 self._counts["out_of_domain"] += 1
134 return
135 cell = self.archive.index_grid(features)
136 if not self.archive.solutions[cell] and self.archive.free < 1:
137 return
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))
142 before = self.archive.nb_added
143 self.archive.add(elite)
144 updates = self.archive.nb_added - before
145 self._counts["archive_updates"] += updates
146 return elite if updates else None
147
148
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.
155
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.
162
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.
167 """
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.")
171 if width > 1:
172 if type(self) is not NeuralMAPElites:
173 raise ValueError("Batched evaluation is available for plain NeuralMAPElites.")
174 return self._train_batched(max_env_steps, width, budget_aware)
175 budget = _StepBudget(max_env_steps, self._counts)
176 with _open_environment(self._factory) as env:
177 _check_spaces(env, self._actor)
178 evaluation = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
179 training = _Cursor(env, self._actor, self._horizon, self._training_rng)
180 while budget.remaining:
181 self._counts["candidate_attempts"] += 1
182 emitter = self._prepare(training, budget)
183 episodes = []
184 for _ in range(self._episodes):
185 episode = _evaluate_episode(evaluation, self._actor, budget, self._transition,
187 if episode is None:
188 break
189 episodes.append(episode)
190 if len(episodes) < self._episodes:
191 break
192 self._counts["evaluated_policies"] += 1
193 self._offer(episodes, emitter)
194 if self._on_step is not None:
195 self._on_step(self.archive, self.stats)
196 return self.stats
197
198 def _train_batched(self, max_env_steps, width, budget_aware):
199 budget = _StepBudget(max_env_steps, self._counts)
200 steps_per_policy = self._episodes * self._horizon if budget_aware else 1
201
202 def affordable_width():
203 return min(width, max(1, budget.remaining // steps_per_policy))
204
205 with ExitStack() as stack:
206 cursors = []
207 for _ in range(affordable_width()):
208 env = stack.enter_context(_open_environment(self._factory))
209 _check_spaces(env, self._actor)
210 cursors.append(_Cursor(env, self._actor, self._horizon, self._evaluation_rng))
211 while budget.remaining:
212 group = cursors[:affordable_width()]
213 genomes = [np.asarray(self._genetic_parameters(), dtype=np.float32) for _ in group]
214 first_id = self._counts["candidate_attempts"] + 1
215 self._counts["candidate_attempts"] += len(genomes)
216 episodes = _evaluate_batch(self._actor, group, genomes, budget, self._evaluation_rng, self._episodes)
217 for candidate_id, (genome, measurements) in enumerate(zip(genomes, episodes), first_id):
218 if len(measurements) == self._episodes:
219 self._counts["evaluated_policies"] += 1
220 self._offer(measurements, "genetic", parameters=genome, candidate_id=candidate_id)
221 if self._on_step is not None:
222 self._on_step(self.archive, self.stats)
223 return self.stats
224
225
226 def policy_for(self, individual, *, device=None, seed=0):
227 """Decode a candidate using this search's observation and action layout."""
228 actor = self._new_actor(seed, device)
229 actor._set_parameters(individual)
230 return actor
231
232
233 def best_policy(self, *, device=None, seed=0):
234 """Return an independent copy of the best policy, or raise on an empty archive."""
235 if self.archive.best is None:
236 raise RuntimeError("The archive contains no evaluated policy.")
237 return self.policy_for(self.archive.best, device=device, seed=seed)
238
239
240
242 """Use a configurable mixture of genetic and PPO-improved offspring.
243
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.
248
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`.
256 """
257
258 _stochastic_box = True
259
260 def __init__(self, env_factory, archive, *, ppo=None, ppo_probability=0.5, **kwargs):
261 self.ppo = PPOConfig() if ppo is None else ppo
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].")
266 self.ppo_probability = ppo_probability
267 super().__init__(env_factory, archive, **kwargs)
268
269 def _prepare(self, cursor, budget):
270 # Reserve the complete post-training evaluation even if every
271 # episode lasts all the way to the external safety horizon.
272 training_limit = budget.remaining - self._episodes * self._horizon
273 if (training_limit <= 0 or not self._can_select() or not self.ppo_probability
274 or self._selection_rng.random() >= self.ppo_probability):
275 return super()._prepare(cursor, budget)
276
277 self._actor._set_parameters(self._parent())
278 learner = _Learner(self._actor, self.ppo, _seed(self._training_rng))
279 cursor.reset()
280 learner.update(cursor, budget, training_limit)
281 self._counts["ppo_offspring"] += 1
282 return "ppo"
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Definition search.py:24
_build_actor(self, env, config, seed, device)
Definition search.py:92
policy_for(self, individual, *, device=None, seed=0)
Rebuild an independent inference actor from an archived genome.
Definition search.py:226
_offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None)
Definition search.py:119
_prepare(self, cursor, budget)
Definition search.py:115
train(self, max_env_steps, *, evaluation_batch_size=1, budget_aware=False)
Spend an additional hard step budget on policy search.
Definition search.py:153
best_policy(self, *, device=None, seed=0)
Rebuild the best archived actor for inference or export.
Definition search.py:233
_train_batched(self, max_env_steps, width, budget_aware)
Definition search.py:198
_new_actor(self, seed, device=None)
Definition search.py:112
Combine genetic variation with fresh PPO updates on copied elites.
Definition search.py:241