62 """Mix Iso+LineDD and action sequence crossover in each generation.
64 Draw the policy to mutate from the archive and a donor episode from
65 the preceding evaluated batch, including rejected candidates. Compare
66 the two rewards-to-go on their original trajectories. Compute the
67 parent's actions on the donor's observations, and use a vector-Jacobian
68 product to apply performance-weighted action differences. This
69 gradient operation uses stored episodes and spends no environment
70 steps. Gymnasium evaluation uses the synchronous NeuralMAPElites loop.
72 :param env_factory: Factory for a single environment with a finite floating-point Box action space.
73 :param archive: Empty, parentless, best-only objective Grid or CVTGrid.
74 :param batch_size: Candidates proposed from a frozen archive per generation.
75 :param genetic_offspring: Number of Iso+LineDD proposals per post-warmup generation.
76 :param gradient_steps: Policy parameter updates for each ASCII offspring.
77 :param gradient_batch_size: Maximum number of offspring per vectorized gradient update.
78 :param learning_rate: Alpha before normalization by prefix length and squared bandwidth.
79 :param bandwidth: RBF length scale in normalized action coordinates.
80 :param state_floor: Minimum state cosine similarity weight.
81 :param clip_threshold: Action kernel threshold for suppressing negative-gain variation.
82 :param gamma: Discount factor for timestep rewards-to-go.
83 :param kwargs: NeuralMAPElites settings. Use one evaluated episode per candidate.
86 def __init__(self, env_factory, archive, *, batch_size=8, genetic_offspring=None, gradient_steps=2,
87 gradient_batch_size=16, learning_rate=.05, bandwidth=.5, state_floor=.25, clip_threshold=.8,
89 if kwargs.get(
"evaluation_episodes", 1) != 1:
90 raise ValueError(
"ASCII-ME uses one complete evaluation episode per candidate.")
91 square = bandwidth * bandwidth
92 if not (0 < learning_rate < np.inf
and 0 < bandwidth
and 0 < square < np.inf
93 and 0 <= state_floor <= 1
and 0 <= clip_threshold <= 1
and 0 <= gamma <= 1):
94 raise ValueError(
"Use finite positive scales and weights or discounts in [0, 1].")
95 self.
batch_size = _integer(batch_size,
"batch_size")
97 else _integer(genetic_offspring,
"genetic_offspring", 0))
99 raise ValueError(
"genetic_offspring must fit within batch_size.")
104 super().__init__(env_factory, archive, **kwargs)
108 def _build_actor(self, env, config, seed, device):
109 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
113 """Return measured steps and the total offline mutation work."""
116 def _prepare(self, cursor, budget):
118 self.
_counts[
"genetic_offspring"] += 1
119 return super()._prepare(cursor, budget)
123 self.
_actor._set_parameters(vector)
124 self.
_counts[
"ascii_offspring" if operator ==
"ascii" else "genetic_offspring"] += 1
127 def _offer(self, episodes, emitter):
128 episode = episodes[0]
129 trajectory =
_Trajectory(episode.observations[:-1].reshape(episode.steps, -1).copy(),
130 self.
_actor._encode_actions(np.asarray(episode.actions).reshape(episode.steps, -1)),
131 _reward_to_go(episode.rewards, self.
_gamma))
132 elite = super()._offer(episodes, emitter)
133 if elite
is not None:
134 elite.scores[_TRAJECTORY] = trajectory
135 self.
_recent.append(trajectory)
138 def _build_generation(self):
141 parents = [self.
_parent()
for _
in range(remaining)]
146 proposals.extend((
"ascii", vector)
for vector
in self.
_mutate(candidates, targets))
149 def _mutate(self, parents, donors):
150 stored = [parent.scores[_TRAJECTORY]
for parent
in parents]
151 lengths = [min(len(source.returns), len(donor.returns))
for source, donor
in zip(stored, donors)]
152 height = max(lengths)
153 states = np.zeros((len(parents), height, stored[0].states.shape[1]), dtype=np.float32)
154 donor_states = np.zeros_like(states)
155 donor_actions = np.zeros((len(parents), height, donors[0].actions.shape[1]), dtype=np.float32)
156 gains = np.zeros((len(parents), height), dtype=np.float32)
157 for row, (source, donor, length)
in enumerate(zip(stored, donors, lengths)):
158 states[row, :length] = source.states[:length]
159 donor_states[row, :length] = donor.states[:length]
160 donor_actions[row, :length] = donor.actions[:length]
161 gains[row, :length] = donor.returns[:length] - source.returns[:length]
162 states, donor_states, donor_actions, gains = map(self.
_actor._tensor,
163 (states, donor_states, donor_actions, gains))
164 rate = self.
_actor._tensor([self.
_rate / (length * self.
_bandwidth**2)
for length
in lengths])[:,
None]
165 network = self.
_actor._network
166 parameters = tuple(network.named_parameters())
167 vectors = self.
_actor._tensor(np.asarray([list(parent)
for parent
in parents], dtype=np.float32))
168 widths = tuple(p.numel()
for _, p
in parameters)
170 def actions_on(weights, observations):
171 return torch.func.functional_call(network, weights, (observations,)).tanh()
173 with torch.enable_grad():
175 vectors.requires_grad_(
True)
176 weights = {name: part.reshape(len(parents), *parameter.shape)
177 for (name, parameter), part
in zip(parameters, vectors.split(widths, dim=1))}
178 outputs = torch.vmap(actions_on)(weights, donor_states)
179 with torch.no_grad():
180 coefficients = _weights(states, donor_states, outputs, donor_actions, gains,
182 directions = coefficients[...,
None] * (donor_actions - outputs)
183 gradient, = torch.autograd.grad(outputs, vectors, grad_outputs=directions)
184 vectors = (vectors + rate * gradient).detach()
185 if not torch.isfinite(vectors).all():
186 raise ValueError(
"ASCII mutation produced nonfinite actor parameters.")
188 return vectors.cpu().numpy()