QDpy
Loading...
Searching...
No Matches
descriptor_search.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Descriptor-conditioned gradient variation for native QDpy archives."""
6
7from collections import deque
8from dataclasses import dataclass
9from enum import IntEnum
10from math import isfinite, prod
11
12import numpy as np
13import torch
14
15from .descriptor_policy import DescriptorConditionedPolicy, _DescriptorDomain
16from .policy import ContinuousPolicy, _integer
17from .rollout import _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
18from .search import NeuralMAPElites
19from .td3 import OffPolicyStats, TD3Config, _Replay, _TD3Learner, _step_actor
20
21
22
23@dataclass(frozen=True)
25 """Count environment interactions, archive operators, and conditioned replay.
26
27 The inherited ``training_steps`` field counts DCG actor collection.
28 The inherited ``evaluation_steps`` field counts archive candidate scoring.
29
30 :param genetic_offspring: Iso+LineDD candidates started after initialization.
31 :param actor_evaluation_attempts: Replay-only actor episodes started by DCG.
32 :param actor_evaluations: Completed replay-only actor episodes in DCG.
33 :param unlabeled_steps: Steps in budget-cut episodes omitted from conditioned replay.
34 """
35
36 genetic_offspring: int = 0
37 actor_evaluation_attempts: int = 0
38 actor_evaluations: int = 0
39 unlabeled_steps: int = 0
40
41
42class _Operator(IntEnum):
43 RANDOM = 0
44 GENETIC = 1
45 PG = 2
46 ACTOR_EVALUATION = 3
47 INJECTION = 4
48
49
50_OFFSPRING_COUNTERS = {
51 _Operator.GENETIC: "genetic_offspring",
52 _Operator.PG: "pg_offspring",
53 _Operator.INJECTION: "actor_injections",
54}
55
56
57@dataclass(frozen=True)
59 operator: _Operator
60 parameters: np.ndarray
61 target: np.ndarray | None = None
62
63
64def _similarity_rewards(rewards, achieved, targets, length_scale):
65 """Scale the unchanged task rewards by distance in normalized coordinates."""
66 # Compute the ratio in float64 so a positive length scale below the
67 # float32 range still gives a similarity of one for identical goals.
68 distance = torch.linalg.vector_norm(achieved.double() - targets.double(), dim=-1)
69 return rewards * (-distance / length_scale).exp().to(rewards.dtype)
70
71
73 """Hold both episode labels and raw TD3 data in the same FIFO rows."""
74
75 def __init__(self, capacity, actor, dimension, length_scale):
76 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
77 self.actor = actor
78 self.achieved = np.empty((capacity, dimension), dtype=np.float32)
79 self.targets = np.empty_like(self.achieved)
80 self.operators = np.empty(capacity, dtype=np.uint8)
81 self.length_scale = length_scale
82
83 def add_episode(self, episode, achieved, proposal):
84 target = achieved if proposal.target is None else proposal.target
85 rewards = np.asarray(episode.rewards, dtype=np.float64)
86 if not np.all((rewards >= 0) & (rewards <= np.finfo(np.float32).max)):
87 raise ValueError("Descriptor-conditioned TD3 requires nonnegative step rewards representable in float32.")
88 count = episode.steps
89 if not count:
90 return
91 # Only the newest capacity rows survive if one episode wraps the ring.
92 start = max(0, count - self.capacity)
93 rows = (self.position + np.arange(start, count)) % self.capacity
94 observations = episode.observations.reshape(count + 1, -1)
95 actions = np.asarray(episode.actions, dtype=np.float64).reshape(count, -1)[start:]
96 self.actions[rows] = self.actor._encode_actions(actions)
97 self.observations[rows] = observations[start:-1]
98 self.next_observations[rows] = observations[start + 1:]
99 self.rewards[rows] = rewards[start:]
100 self.terminated[rows] = False
101 self.terminated[rows[-1]] = episode.terminated
102 self.achieved[rows], self.targets[rows], self.operators[rows] = achieved, target, proposal.operator
103 self.position = (self.position + count) % self.capacity
104 self.size = min(self.size + count, self.capacity)
105
106 def batch(self, rows, device):
107 observations, actions, rewards, successors, terminated = super().batch(rows, device)
108 targets = torch.as_tensor(self.targets[rows], device=device)
109 achieved = torch.as_tensor(self.achieved[rows], device=device)
110 return (torch.cat((observations, targets), dim=-1), actions,
111 _similarity_rewards(rewards, achieved, targets, self.length_scale),
112 torch.cat((successors, targets), dim=-1), terminated)
113
114
116 """Share the conditioned learner, scoring, and budget across DCG and DCRL."""
117
118 _pg_target_in_replay = False
119
120 def __init__(self, env_factory, archive, *, td3, genetic_offspring, pg_offspring, initial_policies,
121 critic_steps, pg_steps, pg_learning_rate, length_scale, **kwargs):
122 self.td3 = TD3Config() if td3 is None else td3
123 if not isinstance(self.td3, TD3Config):
124 raise TypeError("td3 must be a TD3Config.")
125 self.genetic_offspring = _integer(genetic_offspring, "genetic_offspring", 0)
126 self.pg_offspring = _integer(pg_offspring, "pg_offspring", 0)
127 self.critic_steps = _integer(critic_steps, "critic_steps")
128 self.pg_steps = _integer(pg_steps, "pg_steps")
129 if not isfinite(pg_learning_rate) or pg_learning_rate <= 0:
130 raise ValueError("pg_learning_rate must be finite and positive.")
131 if not isfinite(length_scale) or length_scale <= 0:
132 raise ValueError("length_scale must be finite and positive.")
133 self.pg_learning_rate = pg_learning_rate
134 initial = self.genetic_offspring + self.pg_offspring + self._injection_count
135 if not initial:
136 raise ValueError("Allocate at least one archive offspring per generation.")
137 super().__init__(env_factory, archive,
138 initial_policies=initial if initial_policies is None else initial_policies, **kwargs)
139 self._domain = _DescriptorDomain(archive.features_domain)
140 self._conditioned = DescriptorConditionedPolicy._from_layout(
141 self._actor._obs_shape, self._actor._actions, self._domain, self._actor.config,
142 _seed(self._training_rng), self._actor.device,
143 )
144 self._learner = self._make_learner(length_scale)
145 self._goals = np.random.default_rng(_seed(self._training_rng))
146 self._generation = deque()
147
148 def _make_learner(self, length_scale):
149 replay = _ConditionedReplay(self.td3.replay_capacity, self._actor, len(self._domain.bounds), length_scale)
150 return _TD3Learner(self._conditioned._model, self.td3, _seed(self._training_rng),
151 self._counts, replay=replay)
152
153 def _build_actor(self, env, config, seed, device):
154 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
155
156 @property
157 def stats(self):
158 """Return cumulative budgets, completed evaluations, and replay size."""
159 return DescriptorTrainingStats(**self._counts, replay_size=self._learner.replay.size)
160
161
162 def conditioned_policy(self, *, device=None):
163 """Return an actor that accepts a target descriptor in physical units."""
164 model = self._conditioned._model
165 copy = DescriptorConditionedPolicy._from_layout(
166 self._actor._obs_shape, model._actions, self._domain, model.config, 0,
167 model.device if device is None else device,
168 )
169 copy._model._set_parameters(model._parameters())
170 return copy
171
172 def _improve(self, parent, goal):
173 actor = self.policy_for(parent)
174 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=self.pg_learning_rate)
175 replay = self._learner.replay
176 target = actor._tensor(goal)
177 for _ in range(self.pg_steps):
178 obs = replay.sample_observations(self.td3.batch_size, self._learner.sample_rng, actor.device)
179 critic_input = torch.cat((obs, target.expand(len(obs), -1)), dim=-1)
180 _step_actor(actor, optimizer, self._learner.critics[0], obs, critic_observations=critic_input)
181 self._counts["policy_gradient_steps"] += 1
182 self._counts["optimizer_steps"] += 1
183 return _Proposal(_Operator.PG, actor._parameters(), goal if self._pg_target_in_replay else None)
184
185 def _train_learner(self):
186 for _ in range(self.critic_steps):
187 self._learner.update()
188
189 def _build_generation(self):
190 self._train_learner()
191 proposals = [_Proposal(_Operator.GENETIC, self._genetic_parameters())
192 for _ in range(self.genetic_offspring)]
193 for _ in range(self.pg_offspring):
194 parent = self._parent()
195 proposals.append(self._improve(parent, self._domain.normalize(parent.features.values, goal=True)))
196 return self._add_actor_proposals(proposals)
197
198 def _prepare_proposal(self):
199 if not self._generation:
200 steps = self._counts["evaluation_steps"] + self._counts["training_steps"]
201 if not self._can_select() or not self._learner.ready(steps):
202 return _Proposal(_Operator.RANDOM, self._new_actor(_seed(self._actor_rng))._parameters())
203 self._generation.extend(self._build_generation())
204 return self._generation.popleft()
205
206
207 def train(self, max_env_steps):
208 """Continue the search and keep unstarted proposals queued across calls."""
209 budget = _StepBudget(max_env_steps, self._counts)
210 with _open_environment(self._factory) as env:
211 _check_spaces(env, self._actor)
212 evaluation = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
213 collection = _Cursor(env, self._actor, self._horizon, self._training_rng)
214 while budget.remaining:
215 proposal = self._prepare_proposal()
216 self._evaluate_proposal(proposal, evaluation, collection, budget)
217 return self.stats
218
219 def _collect_episode(self, cursor, budget, phase, proposal):
220 episode = _evaluate_episode(cursor, self._actor, budget, phase=phase)
221 if episode is None:
222 return None, None
223 achieved = np.array(self._descriptor(episode), dtype=np.float64, copy=True)
224 self._learner.replay.add_episode(episode, self._domain.normalize(achieved), proposal)
225 return episode, achieved
226
227 def _evaluate_proposal(self, proposal, evaluation, collection, budget):
228 operator = proposal.operator
229 auxiliary = operator == _Operator.ACTOR_EVALUATION
230 if auxiliary:
231 self._counts["actor_evaluation_attempts"] += 1
232 else:
233 self._counts["candidate_attempts"] += 1
234 key = _OFFSPRING_COUNTERS.get(operator)
235 if key is not None:
236 self._counts[key] += 1
237
238 self._actor._set_parameters(proposal.parameters)
239 cursor = collection if auxiliary else evaluation
240 phase = "training_steps" if auxiliary else "evaluation_steps"
241 episodes, descriptors = [], []
242 for _ in range(1 if auxiliary else self._episodes):
243 before = budget.remaining
244 episode, achieved = self._collect_episode(cursor, budget, phase, proposal)
245 if episode is None:
246 self._counts["unlabeled_steps"] += before - budget.remaining
247 return
248 episodes.append(episode)
249 descriptors.append(achieved)
250 if auxiliary:
251 self._counts["actor_evaluations"] += 1
252 return
253
254 self._counts["evaluated_policies"] += 1
255 self._offer(episodes, operator.name.lower(), descriptors=descriptors)
256 if self._on_step is not None:
257 self._on_step(self.archive, self.stats)
258
259
260
262 """Implement the GECCO 2023 replay and offspring schedule.
263
264 In each post-warmup generation the trained actor collects replay-only
265 episodes at perturbed elite descriptors. Genetic and PG offspring fill
266 the archive batch. The PG critic is conditioned on the parent's
267 descriptor during variation. All archive candidates label the replay
268 target with their own measured episode descriptor.
269
270 :param env_factory: Gymnasium factory with bounded floating Box actions.
271 :param archive: Best-only Grid or CVTGrid with finite descriptor bounds.
272 :param td3: Replay and learner settings as a :class:`TD3Config`.
273 :param genetic_offspring: Iso+LineDD archive candidates per generation.
274 :param pg_offspring: Descriptor-conditioned PG candidates per generation.
275 :param actor_evaluations: Additional replay-only episodes per generation.
276 Defaults to the size of the archive offspring batch.
277 :param goal_noise: Standard deviation of active target perturbations
278 in normalized coordinates. Targets are clipped to the domain.
279 :param initial_policies: Random archive candidates before learning.
280 Defaults to the number of archive slots in one generation.
281 :param critic_steps: TD3 critic updates per generation.
282 :param pg_steps: Updates per copy of a parent selected for PG variation.
283 :param pg_learning_rate: Adam learning rate for PG variation.
284 :param length_scale: Positive kernel scale in normalized Euclidean units.
285 :param kwargs: Policy, scoring, and variation options from
286 :class:`NeuralMAPElites`. Step rewards must be nonnegative.
287 """
288
289 _injection_count = 0
290
291 def __init__(self, env_factory, archive, *, td3=None, genetic_offspring=4, pg_offspring=4,
292 actor_evaluations=None, goal_noise=0.1, initial_policies=None, critic_steps=16,
293 pg_steps=4, pg_learning_rate=5e-3, length_scale=0.1, **kwargs):
294 self.actor_evaluations = (
295 _integer(genetic_offspring, "genetic_offspring", 0) + _integer(pg_offspring, "pg_offspring", 0)
296 if actor_evaluations is None else _integer(actor_evaluations, "actor_evaluations", 0)
297 )
298 if not isfinite(goal_noise) or goal_noise < 0:
299 raise ValueError("goal_noise must be finite and nonnegative.")
300 self.goal_noise = goal_noise
301 super().__init__(env_factory, archive, td3=td3, genetic_offspring=genetic_offspring,
302 pg_offspring=pg_offspring, initial_policies=initial_policies, critic_steps=critic_steps,
303 pg_steps=pg_steps, pg_learning_rate=pg_learning_rate, length_scale=length_scale, **kwargs)
304
305 def _add_actor_proposals(self, proposals):
306 active = []
307 for _ in range(self.actor_evaluations):
308 center = self._domain.normalize(self._parent().features.values, goal=True)
309 goal = np.clip(center + self._goals.normal(0, self.goal_noise, size=len(center)), -1, 1).astype(np.float32)
310 actor = self._conditioned._specialize(goal)
311 active.append(_Proposal(_Operator.ACTOR_EVALUATION, actor._parameters(), goal))
312 return active + proposals
313
314
315
317 """Implement the actor-injection schedule from the 2024 DCRL paper.
318
319 Genetic and PG variation complement injected actors specialized at
320 uniformly drawn target descriptors. These actors use the same genome
321 representation as archive elites. PG offspring retain the parent's
322 descriptor as their replay target. Injections retain their sampled
323 target. All candidates compete in the cell they actually reach.
324
325 :param env_factory: Gymnasium factory with bounded floating Box actions.
326 :param archive: Best-only Grid or CVTGrid with finite descriptor bounds.
327 :param injections: Actor injection slots per generation. Set to zero
328 for the no-injection ablation.
329 :param kwargs: Learner, offspring, and scoring options as in
330 :class:`DCGMAPElites`. Initial population size includes injections.
331 """
332
333 _pg_target_in_replay = True
334
335 def __init__(self, env_factory, archive, *, td3=None, genetic_offspring=4, pg_offspring=2,
336 injections=2, initial_policies=None, critic_steps=16, pg_steps=4,
337 pg_learning_rate=5e-3, length_scale=0.1, **kwargs):
338 self._injection_count = _integer(injections, "injections", 0)
339 super().__init__(env_factory, archive, td3=td3, genetic_offspring=genetic_offspring,
340 pg_offspring=pg_offspring, initial_policies=initial_policies, critic_steps=critic_steps,
341 pg_steps=pg_steps, pg_learning_rate=pg_learning_rate, length_scale=length_scale, **kwargs)
342
343 def _add_actor_proposals(self, proposals):
344 for _ in range(self._injection_count):
345 goal = self._goals.uniform(-1, 1, size=len(self._domain.bounds)).astype(np.float32)
346 actor = self._conditioned._specialize(goal)
347 proposals.append(_Proposal(_Operator.INJECTION, actor._parameters(), goal))
348 return proposals
Use descriptor-conditioned gradients and separate actor collection in MAP-Elites.
Add specialized conditioned actors to the MAP-Elites offspring batch.
Separate the costs of replay-only actor evaluations and archive candidates.
_evaluate_proposal(self, proposal, evaluation, collection, budget)
train(self, max_env_steps)
Spend a hard budget on archive candidates and any replay-only actor episodes.
_collect_episode(self, cursor, budget, phase, proposal)
conditioned_policy(self, *, device=None)
Rebuild an independent copy of the shared conditioned actor.
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
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
_offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None)
Definition search.py:119
_new_actor(self, seed, device=None)
Definition search.py:112
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25