QDpy
Loading...
Searching...
No Matches
ascii_me.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""ASCII-ME with batched differentiable mutation and Gymnasium rollouts."""
7
8from collections import deque
9from dataclasses import dataclass
10
11import numpy as np
12import torch
13from torch.nn.functional import cosine_similarity
14
15from .policy import ContinuousPolicy, _integer
16from .rollout import TrainingStats
17from .search import NeuralMAPElites
18
19__all__ = ["ASCIIME", "ASCIIMEStats"]
20
21_TRAJECTORY = "ascii_trajectory"
22
23
24def _reward_to_go(rewards, gamma):
25 result = np.empty(len(rewards), dtype=np.float32)
26 value = 0.
27 for t in range(len(rewards) - 1, -1, -1):
28 value = rewards[t] + gamma * value
29 result[t] = value
30 if not np.isfinite(result).all():
31 raise ValueError("Discounted returns must be finite float32 values.")
32 return result
33
34
35def _weights(states, donor_states, actions, donor_actions, gains, bandwidth, floor, epsilon):
36 """Compute the signed action interpolation coefficients of equations 13–15."""
37 similarity = cosine_similarity(states, donor_states, dim=-1).clamp(min=floor, max=1.)
38 squared = ((actions - donor_actions) / bandwidth).square().sum(dim=-1)
39 kernel = torch.exp(-.5 * squared)
40 return torch.where((kernel < epsilon) & (gains < 0), 0., similarity * kernel * gains)
41
42
43@dataclass(frozen=True)
45 states: np.ndarray
46 actions: np.ndarray
47 returns: np.ndarray
48
49
50
51@dataclass(frozen=True)
53 """Optimizer steps count one update per mutated policy per gradient pass."""
54
55 ascii_offspring: int = 0
56 genetic_offspring: int = 0
57 buffered_episodes: int = 0
58
59
60
62 """Mix Iso+LineDD and action sequence crossover in each generation.
63
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.
71
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.
84 """
85
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,
88 gamma=.99, **kwargs):
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")
96 self.genetic_offspring = (self.batch_size // 2 if genetic_offspring is None
97 else _integer(genetic_offspring, "genetic_offspring", 0))
98 if self.genetic_offspring > self.batch_size:
99 raise ValueError("genetic_offspring must fit within batch_size.")
100 self._gradient_steps = _integer(gradient_steps, "gradient_steps")
101 self._gradient_batch_size = _integer(gradient_batch_size, "gradient_batch_size")
102 self._rate, self._bandwidth = learning_rate, bandwidth
103 self._floor, self._clip, self._gamma = state_floor, clip_threshold, gamma
104 super().__init__(env_factory, archive, **kwargs)
105 self._generation = deque()
106 self._recent = deque(maxlen=self.batch_size)
107
108 def _build_actor(self, env, config, seed, device):
109 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
110
111 @property
112 def stats(self):
113 """Return measured steps and the total offline mutation work."""
114 return ASCIIMEStats(**self._counts, buffered_episodes=len(self._recent))
115
116 def _prepare(self, cursor, budget):
117 if not self._can_select() or not self._recent:
118 self._counts["genetic_offspring"] += 1
119 return super()._prepare(cursor, budget)
120 if not self._generation:
121 self._build_generation()
122 operator, vector = self._generation.popleft()
123 self._actor._set_parameters(vector)
124 self._counts["ascii_offspring" if operator == "ascii" else "genetic_offspring"] += 1
125 return operator
126
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)
136 return elite
137
138 def _build_generation(self):
139 proposals = [("genetic", self._genetic_parameters()) for _ in range(self.genetic_offspring)]
140 remaining = self.batch_size - self.genetic_offspring
141 parents = [self._parent() for _ in range(remaining)]
142 donors = [self._recent[self._training_rng.integers(len(self._recent))] for _ in range(remaining)]
143 for offset in range(0, remaining, self._gradient_batch_size):
144 candidates = parents[offset:offset + self._gradient_batch_size]
145 targets = donors[offset:offset + self._gradient_batch_size]
146 proposals.extend(("ascii", vector) for vector in self._mutate(candidates, targets))
147 self._generation.extend(proposals)
148
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)
169
170 def actions_on(weights, observations):
171 return torch.func.functional_call(network, weights, (observations,)).tanh()
172
173 with torch.enable_grad():
174 for _ in range(self._gradient_steps):
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,
181 self._bandwidth, self._floor, self._clip)
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.")
187 self._counts["optimizer_steps"] += len(parents) * self._gradient_steps
188 return vectors.cpu().numpy()
Count measured episodes and policy-gradient variation independently.
Definition ascii_me.py:52
Optimize deterministic Box policies using archive and rollout-buffer crossover.
Definition ascii_me.py:61
_mutate(self, parents, donors)
Definition ascii_me.py:149
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
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