QDpy
Loading...
Searching...
No Matches
qdpg.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""The two-objective generation schedule from Pierrot et al. (GECCO 2022)."""
6
7from collections import deque
8from copy import deepcopy
9from dataclasses import dataclass
10from math import isfinite, prod
11
12import numpy as np
13from scipy.spatial import cKDTree
14from scipy.spatial.distance import cdist
15import torch
16
17from .policy import ContinuousPolicy, _integer
18from .rollout import TrainingStats, _seed
19from .search import NeuralMAPElites
20from .td3 import TD3Config, _Replay, _checked_step, _critic_loss, _polyak, _step_actor, _td3_targets, _twin_critics
21
22
23
24@dataclass(frozen=True)
26 """Describe executed optimizer steps and started offspring evaluations.
27
28 :param critic_updates: Combined number of optimizer steps for both critic pairs.
29 Each step averages the critic gradients from one half of the generation.
30 :param policy_gradient_steps: Optimizer steps on copied archive actors.
31 :param quality_offspring: Evaluations started with a quality-gradient proposal.
32 :param diversity_offspring: Evaluations started with a diversity-gradient proposal.
33 :param replay_size: Number of transitions currently stored in replay.
34 :param novelty_size: Number of state descriptors currently held for novelty.
35 :param novelty_admissions: Total accepted state descriptors, including evicted ones.
36 """
37
38 critic_updates: int = 0
39 policy_gradient_steps: int = 0
40 quality_offspring: int = 0
41 diversity_offspring: int = 0
42 replay_size: int = 0
43 novelty_size: int = 0
44 novelty_admissions: int = 0
45
46
48 """A FIFO ring of state descriptors admitted by a strict mean-kNN threshold."""
49
50 def __init__(self, capacity, dimension, neighbors, threshold, metric):
51 self.data = np.empty((capacity, dimension), dtype=np.float64)
52 self.neighbors, self.threshold = neighbors, threshold
53 self.metric = cdist if metric is None else metric
54 self.size = self.admissions = 0
55 self._index = None
56
57 def score(self, descriptors):
58 if not self.size:
59 return np.zeros(len(descriptors), dtype=np.float64)
60 points = self.data[:self.size].view()
61 points.flags.writeable = False
62 distances = np.asarray(self.metric(descriptors, points), dtype=np.float64)
63 if (distances.shape != (len(descriptors), self.size) or not np.isfinite(distances).all()
64 or np.any(distances < 0)):
65 raise ValueError("novelty_metric must return a finite, nonnegative distance matrix.")
66 k = min(self.neighbors, self.size)
67 closest = np.partition(distances, k - 1, axis=1)[:, :k]
68 return np.sum(closest / k, axis=1)
69
70 def replay_score(self, descriptors):
71 """Reuse an exact index during replay when the Euclidean workload is small-dimensional."""
72 if not (self.metric is cdist and self.size >= 512 and self.data.shape[1] <= 8
73 and self.neighbors <= 32 and len(descriptors) > 1):
74 return self.score(descriptors)
75 # Keep the distance arithmetic of both paths inside float64 range.
76 limit = 1e150
77 if np.any(np.abs(descriptors) > limit):
78 return self.score(descriptors)
79 if self._index is None:
80 points = self.data[:self.size]
81 if np.any(np.abs(points) > limit):
82 return self.score(descriptors)
83 self._index = cKDTree(points, copy_data=True)
84 distances = self._index.query(descriptors, k=list(range(1, self.neighbors + 1)))[0]
85 return np.sum(distances / self.neighbors, axis=1)
86
87 def add(self, descriptor):
88 if self.size and self.score(descriptor[None, :])[0] <= self.threshold:
89 return
90 self._index = None
91 self.data[self.admissions % len(self.data)] = descriptor
92 self.admissions += 1
93 self.size = min(self.admissions, len(self.data))
94
95
97 """Store the pre-action descriptor in the same row as its transition."""
98
99 def __init__(self, capacity, actor, dimension):
100 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
101 self.descriptors = np.empty((capacity, dimension), dtype=np.float64)
102 self.actor = actor
103
104 def add_transition(self, observation, action, reward, successor, terminated, descriptor):
105 row = self.position
106 self.add(observation, self.actor._encode(action), reward, successor, terminated)
107 self.descriptors[row] = descriptor
108
109
110@dataclass
112 """An archive copy with a private policy target and optimizer for this generation."""
113
114 actor: ContinuousPolicy
115 target: torch.nn.Module
116 optimizer: torch.optim.Optimizer
117
118
120 """Share one independently trained TD3 critic pair across a half-generation."""
121
122 def __init__(self, actor, config, rng):
123 self.config = config
124 self.device = actor.device
125 self.rng = rng
126 self.noise_rng = torch.Generator(device=self.device).manual_seed(_seed(rng))
127 self.critics = _twin_critics(actor, config, rng, rng)
128 self.targets = deepcopy(self.critics).requires_grad_(False)
129 self.optimizer = torch.optim.SGD(self.critics.parameters(), lr=config.critic_learning_rate)
130 self.critic_updates = self.actor_updates = 0
131
132 def prepare(self, actor):
133 return _PolicyUpdate(
134 actor, deepcopy(actor._network).requires_grad_(False),
135 torch.optim.SGD(actor._trainable_parameters(), lr=self.config.actor_learning_rate),
136 )
137
138 def _sample(self, replay, novelty):
139 rows = self.rng.integers(replay.size, size=self.config.batch_size)
140 observations, actions, rewards, successors, terminated = replay.batch(rows, self.device)
141 if novelty is not None:
142 scores = novelty.replay_score(replay.descriptors[rows])
143 if not np.isfinite(scores).all() or np.any(scores > np.finfo(np.float32).max):
144 raise ValueError("QD-PG requires diversity rewards representable in float32.")
145 rewards = torch.as_tensor(scores, dtype=rewards.dtype, device=self.device)
146 return observations, actions, rewards, successors, terminated
147
148 def update(self, candidates, replay, novelty):
149 """Average the critic gradients, then apply the delayed actor and target updates."""
150 self.optimizer.zero_grad(set_to_none=True)
151 actor_batches = []
152 for candidate in candidates:
153 observations, actions, rewards, successors, terminated = self._sample(replay, novelty)
154 target = _td3_targets(candidate.target, self.targets, self.config, self.noise_rng,
155 actions, rewards, successors, terminated)
156 loss = _critic_loss(self.critics, observations, actions, target)
157 (loss / len(candidates)).backward()
158 actor_batches.append(observations)
159 _checked_step(self.optimizer)
160 self.critic_updates += 1
161 if self.critic_updates % self.config.policy_delay:
162 return
163
164 for candidate, observations in zip(candidates, actor_batches):
165 _step_actor(candidate.actor, candidate.optimizer, self.critics[0], observations)
166 self.actor_updates += 1
167 _polyak(candidate.actor._network, candidate.target, self.config.tau)
168 _polyak(self.critics, self.targets, self.config.tau)
169
170
171
173 """Train half the generation toward task return and half toward state novelty.
174
175 Each objective has a separate pair of shared critics. The algorithm
176 clones elites, fits both critic pairs on a single shared replay buffer,
177 and varies each clone with its assigned gradient. It evaluates every
178 proposal in the environment. Episode descriptors select archive cells,
179 and raw episodic return or the supplied fitness ranks the candidates.
180
181 :param env_factory: Factory for a single Gymnasium environment with bounded
182 floating-point Box actions.
183 :param archive: Best-only QDpy Grid or CVTGrid as in :class:`NeuralMAPElites`.
184 :param state_descriptor: Callable taking the pre-action non-flattened
185 float32 observation and its reset or step info. Return a finite 1-D
186 vector with the same number of coordinates as the episode descriptor.
187 Use state coordinates that have a meaningful relation to the episode
188 descriptor, such as current position and final position.
189 :param td3: Optional :class:`TD3Config` for the replay and twin critics.
190 QD-PG uses SGD and draws replay batches with replacement.
191 ``learning_starts`` can extend the random-policy warmup.
192 :param population_size: Even number of proposals per generation. Unless
193 overridden, also the number of initial random policies.
194 :param gradient_steps_ratio: Optimizer rounds per objective are the floor
195 of this ratio times the number of transitions collected since the
196 start of the previous generation.
197 :param novelty_capacity: Maximum number of admitted timestep descriptors.
198 :param novelty_neighbors: Number of nearest neighbors used in the mean.
199 :param novelty_threshold: An arrival must score strictly above this
200 threshold to enter the novelty archive. The first arrival is accepted.
201 :param novelty_metric: Optional pairwise distance function. Takes query
202 rows and archive rows, and returns a nonnegative (queries, archive)
203 distance matrix. Defaults to Euclidean distance.
204 :param kwargs: Evaluation and policy options for :class:`NeuralMAPElites`.
205 """
206
207 def __init__(self, env_factory, archive, *, descriptor, state_descriptor, td3=None,
208 population_size=4, initial_policies=None, gradient_steps_ratio=0.25,
209 novelty_capacity=10_000, novelty_neighbors=10, novelty_threshold=0.01,
210 novelty_metric=None, **kwargs):
211 if not callable(state_descriptor):
212 raise TypeError("state_descriptor must be callable.")
213 if novelty_metric is not None and not callable(novelty_metric):
214 raise TypeError("novelty_metric must be callable.")
215 self.population_size = _integer(population_size, "population_size", 2)
216 if self.population_size % 2:
217 raise ValueError("population_size must be even.")
218 if not isfinite(gradient_steps_ratio) or gradient_steps_ratio <= 0:
219 raise ValueError("gradient_steps_ratio must be finite and positive.")
220 if not isfinite(novelty_threshold) or novelty_threshold < 0:
221 raise ValueError("novelty_threshold must be finite and nonnegative.")
222 self.gradient_steps_ratio = gradient_steps_ratio
223 self.td3 = (TD3Config(learning_starts=0, batch_size=64, critic_hidden_sizes=(64, 32),
224 actor_learning_rate=0.003, critic_learning_rate=0.003)
225 if td3 is None else td3)
226 if not isinstance(self.td3, TD3Config):
227 raise TypeError("td3 must be a TD3Config.")
228 capacity = _integer(novelty_capacity, "novelty_capacity")
229 neighbors = _integer(novelty_neighbors, "novelty_neighbors")
230 initial = self.population_size if initial_policies is None else initial_policies
231 super().__init__(env_factory, archive, descriptor=descriptor, initial_policies=initial, **kwargs)
232 self._describe_state = state_descriptor
233 dimension = len(archive.features_domain)
234 self._novelty = _NoveltyArchive(capacity, dimension, neighbors, novelty_threshold, novelty_metric)
235 self._replay = _StateReplay(self.td3.replay_capacity, self._actor, dimension)
236 self._diversity, self._quality = (
237 _Objective(self._actor, self.td3, np.random.default_rng(_seed(self._training_rng)))
238 for _ in range(2)
239 )
240 self._previous_steps = 0
241 self._generation = deque()
242
243 def _build_actor(self, env, config, seed, device):
244 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
245
246 @property
247 def stats(self):
248 """Return cumulative training costs, operator counts, and buffer sizes."""
249 critic_updates = self._quality.critic_updates + self._diversity.critic_updates
250 actor_updates = self._quality.actor_updates + self._diversity.actor_updates
251 return QDPGStats(**self._counts, critic_updates=critic_updates, policy_gradient_steps=actor_updates,
252 optimizer_steps=critic_updates + actor_updates, replay_size=self._replay.size,
253 novelty_size=self._novelty.size, novelty_admissions=self._novelty.admissions)
254
255 def _state_descriptor(self, observation, info):
256 value = np.array(self._describe_state(observation.copy(), deepcopy(dict(info))), dtype=np.float64, copy=True)
257 dimension = len(self.archive.features_domain)
258 if value.shape != (dimension,) or not np.isfinite(value).all():
259 raise ValueError(f"Expected a finite state descriptor of length {dimension}.")
260 return value
261
262 def _transition(self, observation, action, reward, successor, terminated, descriptor):
263 self._replay.add_transition(observation, action, reward, successor, terminated, descriptor)
264 self._novelty.add(descriptor)
265
266 def _prepare(self, cursor, budget):
267 if not self._generation:
268 if not self._can_select() or self._counts["evaluation_steps"] < self.td3.learning_starts:
269 self._actor._set_parameters(self._new_actor(_seed(self._actor_rng))._parameters())
270 return "random"
271 self._build_generation()
272 objective, parameters = self._generation.popleft()
273 self._actor._set_parameters(parameters)
274 self._counts[f"{objective}_offspring"] += 1
275 return objective
276
277 def _build_generation(self):
278 steps = self._counts["evaluation_steps"]
279 rounds = int((steps - self._previous_steps) * self.gradient_steps_ratio)
280 generation = []
281 for name, objective, novelty in (
282 ("diversity", self._diversity, self._novelty), ("quality", self._quality, None),
283 ):
284 candidates = []
285 for _ in range(self.population_size // 2):
286 actor = self.policy_for(self._parent(), seed=_seed(self._actor_rng))
287 candidates.append(objective.prepare(actor))
288 for _ in range(rounds):
289 objective.update(candidates, self._replay, novelty)
290 generation.extend((name, candidate.actor._parameters()) for candidate in candidates)
291 self._generation.extend(generation)
292 self._previous_steps = steps
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
Cumulative costs and state novelty archive counts for QD-PG.
Definition qdpg.py:25
Illuminate a bounded continuous control archive with two policy gradients.
Definition qdpg.py:172
tuple _quality
Definition qdpg.py:236
_build_generation(self)
Definition qdpg.py:277
int _previous_steps
Definition qdpg.py:240
replay_score(self, descriptors)
Definition qdpg.py:70
score(self, descriptors)
Definition qdpg.py:57
_sample(self, replay, novelty)
Definition qdpg.py:138
update(self, candidates, replay, novelty)
Definition qdpg.py:148
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
policy_for(self, individual, *, device=None, seed=0)
Rebuild an independent inference actor from an archived genome.
Definition search.py:226
_new_actor(self, seed, device=None)
Definition search.py:112
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25
add(self, observation, action, reward, next_observation, terminated)
Definition td3.py:107