QDpy
Loading...
Searching...
No Matches
pollination.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Continuous-action Pollination MAP-Elites with a hard interaction budget."""
6
7from collections import Counter
8from dataclasses import dataclass
9from math import isfinite
10from numbers import Real
11
12import numpy as np
13import torch
14from torch.nn.functional import mse_loss
15
16from qdpy.algorithms.task_search import _validate_grid
17from qdpy.containers import Grid
18from qdpy.phenotype import Features, Fitness, _CellIndividual
19from .policy import ContinuousPolicy, _integer
20from .rollout import _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
21from .td3 import _checked_step
22
23__all__ = ["PollinationMAPElites", "PollinationStats"]
24
25
26
27@dataclass(frozen=True)
29 """All three step categories count against the hard search budget."""
30
31 evaluation_steps: int = 0
32 teacher_steps: int = 0
33 student_steps: int = 0
34 candidate_attempts: int = 0
35 evaluated_policies: int = 0
36 body_mutations: int = 0
37 migrations: int = 0
38 pollination_rounds: int = 0
39 pollinated: int = 0
40 distillation_updates: int = 0
41
42 @property
43 def env_steps(self):
44 """Return the total number of simulator interactions."""
45 return self.evaluation_steps + self.teacher_steps + self.student_steps
46
47
48
50 """Optimize numeric bodies and deterministic continuous controllers.
51
52 The archive stores a flat body followed by the policy weights. A
53 candidate mutates its body or its controller. A distillation round
54 learns from an occupied cell and up to four occupied Moore neighbors
55 and offers the student on those same bodies using paired reset seeds.
56 The initial rollout, teacher collection, and student trials all spend
57 from the same simulator budget.
58
59 :param env_factory: Callable of a body tuple returning an environment.
60 Every body must provide the same observation and Box action layout.
61 :param archive: Empty, parentless, maximizing best-only two-axis Grid.
62 :param initial_bodies: Iterable of fixed-width finite numeric tuples.
63 :param body_descriptor: Function of a body giving its two bin coordinates.
64 :param mutate_body: Callable of a body and a NumPy generator.
65 :param policy: Optional continuous PolicyConfig.
66 :param body_mutation_probability: Fraction of offspring with body variation.
67 :param controller_sigma: Gaussian scale for controller-only mutations.
68 :param batch_size: Completed offspring per generation.
69 :param pollination_every: Generations between rounds. None disables distillation.
70 :param quality_tolerance: Allowed absolute loss on the matched teacher run.
71 :param distillation_epochs: Supervised passes over collected teacher records.
72 :param distillation_learning_rate: Student Adam step size.
73 :param max_episode_steps: Maximum length of a rollout.
74 :param seed: Root seed for independent search and distillation streams.
75 :param device: CPU or CUDA for the policy.
76 """
77
78 def __init__(self, env_factory, archive, *, initial_bodies, body_descriptor, mutate_body,
79 policy=None, body_mutation_probability=.5, controller_sigma=.1, batch_size=8,
80 pollination_every=500, quality_tolerance=0., distillation_epochs=10,
81 distillation_learning_rate=.003, max_episode_steps=300, seed=0, device="cpu"):
82 _validate_grid(archive)
83 if (type(archive) is not Grid or len(archive.shape) != 2 or archive.fitness_score_names
84 or archive.features_score_names or
85 (archive.fitness_weights is not None and archive.fitness_weights[0] <= 0)):
86 raise ValueError("Use a maximizing two-axis Grid with ordinary fitness and descriptors.")
87 if not all(map(callable, (env_factory, body_descriptor, mutate_body))):
88 raise TypeError("Supply environment, descriptor, and body mutation callables.")
89 if (not 0 <= body_mutation_probability <= 1 or not 0 <= controller_sigma < np.inf
90 or not 0 <= quality_tolerance < np.inf or not 0 < distillation_learning_rate < np.inf):
91 raise ValueError("Use a valid mutation probability, finite scales, and positive learning rate.")
92 bodies = [tuple(body) for body in initial_bodies]
93 if not bodies or not bodies[0]:
94 raise ValueError("Supply at least one nonempty initial body.")
95 self._body_size = len(bodies[0])
96 self._initial = tuple(self._body(body) for body in bodies)
97 self.archive = archive
98 if archive.fitness_weights is None:
99 archive._set_fitness_weights((1.,))
100 self._factory, self._descriptor, self._mutate = env_factory, body_descriptor, mutate_body
101 self._body_probability, self._sigma = body_mutation_probability, controller_sigma
102 self._batch_size = _integer(batch_size, "batch_size")
103 self._period = None if pollination_every is None else _integer(pollination_every, "pollination_every")
104 self._tolerance = quality_tolerance
105 self._epochs = _integer(distillation_epochs, "distillation_epochs")
106 self._rate = distillation_learning_rate
107 self._horizon = _integer(max_episode_steps, "max_episode_steps")
108 self._counts = Counter()
109 self._due = False
110 self._search_rng, self._evaluation_rng, self._teacher_rng = (
111 np.random.default_rng(s) for s in np.random.SeedSequence(seed).spawn(3))
112 with _open_environment(lambda: env_factory(self._initial[0])) as env:
113 self._actor = ContinuousPolicy(env.observation_space, env.action_space, config=policy,
114 seed=_seed(self._search_rng), device=device)
115 self._genome_size = self._body_size + len(self._actor._parameters())
116
117 def _body(self, body):
118 body = tuple(body)
119 if len(body) != self._body_size or not all(isinstance(x, Real) and isfinite(x) for x in body):
120 raise ValueError("A body must contain the configured number of finite numeric coordinates.")
121 return body
122
123 @property
124 def stats(self):
125 """Return cumulative simulator and migration counters."""
126 return PollinationStats(**self._counts)
127
128
129 def body_for(self, individual):
130 """Return the body tuple accepted by the environment factory."""
131 if len(individual) != self._genome_size:
132 raise ValueError("The individual does not match this body and controller layout.")
133 return self._body(individual[:self._body_size])
134
135
136 def policy_for(self, individual, *, device=None):
137 """Return a continuous controller that can be saved and loaded separately."""
138 self.body_for(individual)
139 actor = self._actor._new(0, device)
140 actor._set_parameters(individual[self._body_size:])
141 return actor
142
143 def _evaluate(self, body, actor, budget, rng, phase):
144 with _open_environment(lambda: self._factory(body)) as env:
145 _check_spaces(env, actor)
146 return _evaluate_episode(_Cursor(env, actor, self._horizon, rng), actor, budget, phase=phase)
147
148 def _measure(self, body, actor, episode, name):
149 descriptor = tuple(map(float, self._descriptor(body)))
150 fitness = episode.return_
151 if len(descriptor) != 2 or not all(map(isfinite, descriptor)) or not isfinite(fitness):
152 raise ValueError("Expected finite fitness and two morphology descriptors.")
153 grid = self.archive
154 if not grid.in_bounds(descriptor, grid.features_domain) or not grid.in_bounds((fitness,), grid.fitness_domain):
155 return None
156 cell = grid.index_grid(descriptor)
157 individual = _CellIndividual((*body, *actor._parameters()), cell, name=name,
158 features=Features(descriptor), fitness=Fitness((fitness,), weights=(1.,)))
159 return cell, individual
160
161 def _offspring(self):
162 attempted = self._counts["candidate_attempts"]
163 rng = self._search_rng
164 if attempted < len(self._initial) or not self.archive:
165 body = self._initial[attempted % len(self._initial)]
166 return body, self._actor._new(_seed(rng))._parameters(), None
167 parent = self.archive[rng.integers(len(self.archive))]
168 body, weights = self.body_for(parent), np.asarray(parent[self._body_size:])
169 if rng.random() < self._body_probability:
170 self._counts["body_mutations"] += 1
171 return self._body(self._mutate(body, rng)), weights, self.archive.index_grid(parent)
172 return body, weights + rng.normal(scale=self._sigma, size=len(weights)), None
173
174 def _neighbors(self):
175 grid = self.archive
176 anchor = grid[self._teacher_rng.integers(len(grid))]
177 cell = grid.index_grid(anchor)
178 neighbors = [front[0] for coordinate, front in grid.solutions.items() if front and coordinate != cell
179 and max(abs(a - b) for a, b in zip(coordinate, cell)) <= 1]
180 chosen = self._teacher_rng.choice(len(neighbors), size=min(4, len(neighbors)), replace=False)
181 return [anchor, *(neighbors[i] for i in chosen)]
182
183 def _distill(self, teachers):
184 student = self.policy_for(teachers[0][0])
185 observations = np.concatenate([episode.observations[:-1] for _, _, episode in teachers])
186 actions = np.concatenate([np.asarray(episode.actions).reshape(episode.steps, -1)
187 for _, _, episode in teachers])
188 inputs = student._tensor(observations.reshape(len(actions), -1))
189 targets = student._tensor(student._encode_actions(actions))
190 optimizer = torch.optim.Adam(student._trainable_parameters(), lr=self._rate)
191 for _ in range(self._epochs):
192 order = self._teacher_rng.permutation(len(actions))
193 for start in range(0, len(order), 64):
194 rows = order[start:start + 64]
195 optimizer.zero_grad(set_to_none=True)
196 loss = mse_loss(student._normalized(inputs[rows]), targets[rows])
197 if not torch.isfinite(loss):
198 raise ValueError("Pollination produced a nonfinite imitation loss.")
199 loss.backward()
200 _checked_step(optimizer)
201 self._counts["distillation_updates"] += 1
202 return student
203
204 def _pollinate(self, budget):
205 elites = self._neighbors()
206 if len(elites) < 2:
207 return True
208 teachers = []
209 for elite in elites:
210 seed = _seed(self._teacher_rng)
211 episode = self._evaluate(self.body_for(elite), self.policy_for(elite), budget,
212 np.random.default_rng(seed), "teacher_steps")
213 if episode is None:
214 return False
215 teachers.append((elite, seed, episode))
216 student = self._distill(teachers)
217 replacements = []
218 for elite, seed, teacher in teachers:
219 body = self.body_for(elite)
220 episode = self._evaluate(body, student, budget, np.random.default_rng(seed), "student_steps")
221 if episode is None:
222 return False
223 if episode.return_ >= teacher.return_ - self._tolerance:
224 measurement = self._measure(body, student, episode, f"pollinated-{elite.name}")
225 if measurement is not None:
226 cell, candidate = measurement
227 if cell != self.archive.index_grid(elite):
228 raise ValueError("Body descriptors must remain fixed during pollination.")
229 replacements.append((elite, candidate))
230 for elite, candidate in replacements:
231 self.archive.discard(elite)
232 self.archive.add(candidate)
233 self._counts["pollination_rounds"] += 1
234 self._counts["pollinated"] += len(replacements)
235 return True
236
237
238 def train(self, max_env_steps):
239 """Run the search. A budget-cut distillation round commits no replacements."""
240 budget = _StepBudget(max_env_steps, self._counts)
241 while budget.remaining:
242 if self._due:
243 if not self._pollinate(budget):
244 break
245 self._due = False
246 if not budget.remaining:
247 break
248 body, parameters, parent_cell = self._offspring()
249 self._counts["candidate_attempts"] += 1
250 self._actor._set_parameters(parameters)
251 episode = self._evaluate(body, self._actor, budget, self._evaluation_rng, "evaluation_steps")
252 if episode is None:
253 break
254 self._counts["evaluated_policies"] += 1
255 measured = self._measure(body, self._actor, episode, str(self._counts["candidate_attempts"]))
256 if measured is not None:
257 cell, individual = measured
258 if self.archive.free >= 1 or self.archive.solutions[cell]:
259 before = self.archive.nb_added
260 self.archive.add(individual)
261 if parent_cell is not None and parent_cell != cell and self.archive.nb_added > before:
262 self._counts["migrations"] += 1
263 completed = self._counts["evaluated_policies"]
264 self._due = bool(self.archive and self._period and completed % (self._batch_size * self._period) == 0)
265 return self.stats
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
Illuminate morphology space and periodically distill a shared teacher neighborhood.
policy_for(self, individual, *, device=None)
Decode an independent controller for a body.
_evaluate(self, body, actor, budget, rng, phase)
train(self, max_env_steps)
Spend an additional budget on offspring and scheduled distillation.
body_for(self, individual)
Recover the immutable body coordinates from an archived genome.
_measure(self, body, actor, episode, name)
Search and distillation costs, admissions, and cross-cell body moves.