50 """Optimize numeric bodies and deterministic continuous controllers.
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.
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.
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.")
98 if archive.fitness_weights
is None:
99 archive._set_fitness_weights((1.,))
102 self.
_batch_size = _integer(batch_size,
"batch_size")
103 self.
_period =
None if pollination_every
is None else _integer(pollination_every,
"pollination_every")
105 self.
_epochs = _integer(distillation_epochs,
"distillation_epochs")
106 self.
_rate = distillation_learning_rate
107 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
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:
117 def _body(self, 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.")
125 """Return cumulative simulator and migration counters."""
130 """Return the body tuple accepted by the environment factory."""
132 raise ValueError(
"The individual does not match this body and controller layout.")
137 """Return a continuous controller that can be saved and loaded separately."""
139 actor = self.
_actor._new(0, device)
140 actor._set_parameters(individual[self.
_body_size:])
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)
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.")
154 if not grid.in_bounds(descriptor, grid.features_domain)
or not grid.in_bounds((fitness,), grid.fitness_domain):
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
161 def _offspring(self):
162 attempted = self.
_counts[
"candidate_attempts"]
166 return body, self.
_actor._new(_seed(rng))._parameters(),
None
170 self.
_counts[
"body_mutations"] += 1
172 return body, weights + rng.normal(scale=self.
_sigma, size=len(weights)),
None
174 def _neighbors(self):
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)]
183 def _distill(self, teachers):
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)
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.")
200 _checked_step(optimizer)
201 self.
_counts[
"distillation_updates"] += 1
204 def _pollinate(self, budget):
212 np.random.default_rng(seed),
"teacher_steps")
215 teachers.append((elite, seed, episode))
218 for elite, seed, teacher
in teachers:
220 episode = self.
_evaluate(body, student, budget, np.random.default_rng(seed),
"student_steps")
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:
233 self.
_counts[
"pollination_rounds"] += 1
234 self.
_counts[
"pollinated"] += len(replacements)
239 """Run the search. A budget-cut distillation round commits no replacements."""
241 while budget.remaining:
246 if not budget.remaining:
248 body, parameters, parent_cell = self.
_offspring()
249 self.
_counts[
"candidate_attempts"] += 1
250 self.
_actor._set_parameters(parameters)
254 self.
_counts[
"evaluated_policies"] += 1
256 if measured
is not None:
257 cell, individual = measured
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"]