71 """Append one-hot species inputs at sampling time and retain task and diversity rewards."""
73 def __init__(self, capacity, observations, actions, species, diversity_scale):
74 super().__init__(capacity, observations, actions)
75 self.
labels = np.empty(capacity, dtype=np.intp)
76 self.
bonuses = np.empty(capacity, dtype=np.float32)
79 def add_transition(self, observation, action, reward, successor, terminal, species, bonus):
81 super().add(observation, action, reward, successor, terminal)
84 def conditioned(self, observation, labels):
85 code = F.one_hot(labels, num_classes=self.
species).to(observation.dtype)
86 return torch.cat((observation, code), dim=-1)
88 def batch(self, rows, device):
89 state, action, reward, successor, terminal = super().batch(rows, device)
90 labels = torch.as_tensor(self.
labels[rows], device=device)
91 bonus = torch.as_tensor(self.
bonuses[rows], device=device)
98 """Learn continuous policies using species-specific deterministic policy gradients.
100 Each species contains several independently deployable policies. A
101 discriminator rewards successor states informative about their species.
102 The shared actor and twin critics receive species IDs and learn TD3
103 targets from a common replay ring. Retained members are reevaluated
104 every generation and selected by their running mean task return.
105 Offspring learn against the shared critic using their own species'
106 replay states. An optional post-training audit can map policies into
107 caller-supplied descriptor cells.
109 :param env_factory: Callable returning a single Gymnasium Box environment.
110 :param num_species: Number of fixed, equal-sized populations.
111 :param species_size: Number of policies belonging to each species.
112 :param elites: Number of retained breeders per species, below species_size.
113 :param diversity_scale: Nonnegative multiplier of the discriminator reward.
114 :param gradient_steps: Number of actor updates per cloned offspring.
115 :param update_frequency: Environment steps between replay learner updates.
116 :param discriminator_learning_rate: Positive Adam learning rate for the state classifier.
117 :param policy: PolicyConfig specifying policy and species actor architecture.
118 :param td3: TD3Config for the shared learner and offspring learning rate.
119 :param max_episode_steps: Hard maximum steps in each training or audit episode.
120 :param seed: Nonnegative seed for resets, replay, and variation.
121 :param device: CPU or CUDA Torch device.
124 def __init__(self, env_factory, *, num_species=4, species_size=4, elites=2,
125 diversity_scale=.05, gradient_steps=8, update_frequency=4,
126 discriminator_learning_rate=3e-4, policy=None, td3=None,
127 max_episode_steps=300, seed=0, device="cpu"):
128 if not callable(env_factory):
129 raise TypeError(
"env_factory must be callable.")
130 self.
num_species = _integer(num_species,
"num_species", 2)
131 self.
species_size = _integer(species_size,
"species_size", 2)
132 self.
elites = _integer(elites,
"elites")
134 or diversity_scale > np.finfo(np.float32).max
135 or not 0 < discriminator_learning_rate < np.inf):
136 raise ValueError(
"Use fewer breeders than members, a finite diversity scale, and a positive learning rate.")
139 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
141 seed = _integer(seed,
"seed", 0)
142 self.
_rng, self.
_reset_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
143 config =
TD3Config()
if td3
is None else td3
144 if not isinstance(config, TD3Config):
145 raise TypeError(
"td3 must be a TD3Config.")
146 with _open_environment(env_factory)
as env:
148 seed=_seed(self.
_rng), device=device)
150 observation_count, action_count = prod(parameters._obs_shape), prod(parameters._actions.shape)
151 conditioned = ContinuousPolicy._from_layout((observation_count + self.
num_species,), parameters._actions,
152 parameters.config, _seed(self.
_rng), parameters.device,
154 replay =
_SpeciesReplay(config.replay_capacity, observation_count, action_count,
159 _seed(self.
_rng), parameters.device, nn.ReLU)
168 """Return cumulative search accounting, including pending population work."""
172 def _bonus(self, observation, species):
174 return float(F.log_softmax(logits, dim=-1)[species]) - self.
_log_prior
176 def _record(self, observation, action, reward, successor, terminal, species):
178 replay = learner.replay
179 bonus = self.
_bonus(successor, species)
180 if not isfinite(bonus)
or abs(reward + replay.diversity_scale * bonus) > np.finfo(np.float32).max:
181 raise ValueError(
"DQS needs finite state scores and float32-compatible shaped rewards.")
182 replay.add_transition(observation, self.
_actor._encode(action), reward, successor, terminal, species, bonus)
183 steps = self.
_counts[
"evaluation_steps"]
186 rows = learner.sample_rng.integers(replay.size, size=learner.config.batch_size)
187 device = self.
_actor.device
189 labels = torch.as_tensor(replay.labels[rows], device=device)
190 loss = F.cross_entropy(logits, labels)
191 if not torch.isfinite(loss):
192 raise ValueError(
"DQS produced a nonfinite discriminator loss.")
196 self.
_counts[
"optimizer_steps"] += 1
197 self.
_counts[
"discriminator_updates"] += 1
200 learner, population = self.
_learner, []
201 replay, device = learner.replay, self.
_actor.device
203 elites = sorted(group, key=
lambda member: member.mean, reverse=
True)[:self.
elites]
204 next_group = elites.copy()
205 available = np.flatnonzero(replay.labels[:replay.size] == species)
207 parent = elites[self.
_rng.integers(len(elites))]
208 parameters = parent.parameters.copy()
209 if len(available)
and learner.counts[
"critic_updates"]:
211 actor._set_parameters(parameters)
212 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=learner.config.actor_learning_rate)
214 rows = learner.sample_rng.choice(available, size=learner.config.batch_size, replace=
True)
215 states = actor._tensor(replay.observations[rows])
216 conditioned = replay.conditioned(states, torch.as_tensor(replay.labels[rows], device=device))
217 _step_actor(actor, optimizer, learner.critics[0], states, critic_observations=conditioned)
218 self.
_counts[
"policy_gradient_steps"] += 1
219 self.
_counts[
"optimizer_steps"] += 1
220 parameters = actor._parameters()
221 self.
_counts[
"pg_offspring"] += 1
222 next_group.append(
_Member(parameters))
223 population.append(next_group)
229 """Train for additional environment steps. Retry an unfinished member on the next call."""
232 with _open_environment(self.
_factory)
as env:
233 _check_spaces(env, self.
_actor)
235 while budget.remaining:
236 if self.
_offset == generation_size:
240 self.
_actor._set_parameters(candidate.parameters)
241 self.
_counts[
"candidate_attempts"] += 1
242 before = budget.remaining
244 def record(observation, action, reward, successor, terminal):
245 self.
_record(observation, action, reward, successor, terminal, species)
247 episode = _evaluate_episode(cursor, self.
_actor, budget, on_transition=record)
249 self.
_counts[
"prefix_steps"] += before - budget.remaining
251 if not isfinite(episode.return_):
252 raise ValueError(
"The total task return must be finite.")
253 candidate.record(episode.return_)
255 self.
_counts[
"evaluated_policies"] += 1
256 if self.
_offset == generation_size:
257 self.
_counts[
"generations"] += 1
262 """Return a deterministic ContinuousPolicy for the current slots."""
263 species, member = _integer(species,
"species", 0), _integer(member,
"member", 0)
264 actor = self.
_actor._new(0, device)
265 actor._set_parameters(self.
_population[species][member].parameters)
268 def _measured_members(self, species):
269 return [(index, candidate)
for index, candidate
in enumerate(self.
_population[species])
270 if candidate.episodes]
274 """Optionally restrict selection to one species."""
275 groups = range(self.
num_species)
if species
is None else (_integer(species,
"species", 0),)
276 scored = [(candidate.mean, z, i)
for z
in groups
for i, candidate
in self.
_measured_members(z)]
278 raise RuntimeError(
"No policy has completed a training episode.")
279 _, z, i = max(scored, key=
lambda entry: entry[0])
290 def evaluate(self, *, episodes=4, seed=1337, descriptor=None, archive=None, env_factory=None,
291 best_per_species=False):
292 """Evaluate without updating the search counters, learner, or supplied grid."""
293 episodes, seed = _integer(episodes,
"episodes"), _integer(seed,
"seed", 0)
294 if descriptor
is not None and not callable(descriptor):
295 raise TypeError(
"descriptor must be callable.")
296 if env_factory
is not None and not callable(env_factory):
297 raise TypeError(
"env_factory must be callable.")
299 if archive
is not None:
300 NeuralMAPElites._validate_archive(archive)
301 if descriptor
is None:
302 raise ValueError(
"An audit archive requires a descriptor callback.")
303 output = _stage_archive(archive)
304 counts, rows = Counter(), []
306 factory = self.
_factory if env_factory
is None else env_factory
307 with _open_environment(factory)
as env:
308 _check_spaces(env, self.
_actor)
311 if best_per_species
and group:
312 group = [max(group, key=
lambda item: item[1].mean)]
313 for i, member
in group:
315 cursor =
_Cursor(env, actor, self.
_horizon, np.random.default_rng(seed))
316 measurements = [_evaluate_episode(cursor, actor, budget)
for _
in range(episodes)]
317 returns = tuple(episode.return_
for episode
in measurements)
318 if not all(map(isfinite, returns)):
319 raise ValueError(
"The total task return must be finite.")
320 mean_return = fsum(value / episodes
for value
in returns)
322 if descriptor
is not None:
323 values = np.asarray([descriptor(episode)
for episode
in measurements], dtype=float)
324 if values.ndim != 2
or not values.shape[1]
or not np.isfinite(values).all():
325 raise ValueError(
"Audit descriptors must be finite vectors of equal length.")
326 behavior = tuple((values / episodes).sum(axis=0))
328 if output
is not None:
329 if len(behavior) != len(output.features_domain):
330 raise ValueError(
"Audit descriptor length must match the archive geometry.")
331 if (output.in_bounds(behavior, output.features_domain)
332 and output.in_bounds((mean_return,), output.fitness_domain)):
333 cell = output.index_grid(behavior)
334 if output.free >= 1
or output.solutions[cell]:
336 fitness=
Fitness((mean_return,), weights=(1.,)), features=
Features(behavior)))
337 return DQSAudit(tuple(rows), counts[
"evaluation_steps"], output)