QDpy
Loading...
Searching...
No Matches
cma_mega.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Differentiable QD for continuous-control Gymnasium policies."""
7
8from dataclasses import dataclass
9
10import numpy as np
11import torch
12
13from qdpy.algorithms.descriptor_cma import _losses, _rank_gradients, _strategy
14from qdpy.algorithms.differentiable import _gradient_basis
15
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, _critic, _TD3Learner
20
21
22
23@dataclass(frozen=True)
25 """Report ES work in training_steps and archive-scoring work in evaluation_steps.
26
27 Perturbation attempts include budget-cut attempts. Reward gradient
28 counts measure gradient estimates, which do not update the policy
29 in place or consume environment steps.
30 """
31
32 generations: int = 0
33 perturbation_attempts: int = 0
34 completed_perturbations: int = 0
35 reward_gradients: int = 0
36 restarts: int = 0
37
38
39
41 """Implement the TD3 and ES variant of CMA-MEGA from Tjanaka et al.
42
43 Score the centre, then perturb it in mirrored Gaussian directions.
44 One set of complete probes estimates all descriptor gradients and
45 feeds the TD3 replay. Estimate the reward gradient through Q1 on
46 states sampled from replay. Branch along combinations of unit
47 gradients, adapt CMA from archive improvement and move the centre by
48 rank-weighted recombination. Offer the TD3 greedy policy once per
49 generation and update the TD3 learner for the next generation.
50
51 :param env_factory: Fresh single-environment Gymnasium factory with Box
52 observations and finite floating-point Box actions.
53 :param archive: Empty best-only scalar Grid or CVTGrid maximizing return.
54 :param descriptor: Map a complete Episode to its descriptor coordinates.
55 :param td3: Optional TD3Config.
56 :param batch_size: Number of CMA branches plus one greedy injection.
57 :param es_samples: Even number of mirrored ES perturbations.
58 :param es_sigma: Perturbation standard deviation in flat actor coordinates.
59 :param sigma0: Initial Gaussian scale in gradient coefficient space.
60 :param step_size: Rank-weighted centre ascent step size.
61 :param gradient_batch_size: Number of replay states for the reward gradient.
62 :param critic_steps: Number of TD3 updates after each full generation.
63 :param policy: Optional actor PolicyConfig.
64 :param evaluation_episodes: Number of complete episodes per policy or probe.
65 :param max_episode_steps: Safety step cap per episode.
66 :param seed: Private search and environment-reset seed.
67 :param device: Torch device.
68 :param on_step: Optional archive and stats callback after complete archive scoring.
69 """
70
71 def __init__(self, env_factory, archive, *, descriptor, td3=None, batch_size=8, es_samples=8,
72 es_sigma=.02, sigma0=1., step_size=1., gradient_batch_size=512, critic_steps=16,
73 policy=None, evaluation_episodes=1, max_episode_steps=300, seed=0,
74 device="cpu", on_step=None):
75 try:
76 import cma # noqa: F401
77 except ImportError as error:
78 raise ImportError("CMAMEGATD3ES requires the CMA backend. Install qdpy[rl,cma].") from error
79 self.td3 = TD3Config() if td3 is None else td3
80 if not isinstance(self.td3, TD3Config):
81 raise TypeError("td3 must be a TD3Config.")
82 self.batch_size = _integer(batch_size, "batch_size", 3)
83 self.es_samples = _integer(es_samples, "es_samples", 2)
84 if self.es_samples % 2:
85 raise ValueError("es_samples must be even.")
86 if not all(0. < scale < np.inf for scale in (es_sigma, sigma0, step_size)):
87 raise ValueError("Use finite positive ES noise, CMA scale, and centre step size.")
88 self.gradient_batch_size = _integer(gradient_batch_size, "gradient_batch_size")
89 self.critic_steps = _integer(critic_steps, "critic_steps")
90 self.es_sigma, self.sigma0, self.step_size = es_sigma, sigma0, step_size
91 super().__init__(env_factory, archive, descriptor=descriptor, policy=policy,
92 evaluation_episodes=evaluation_episodes, max_episode_steps=max_episode_steps,
93 seed=seed, device=device, on_step=on_step)
94 self._centre = self._actor._parameters().astype(float)
95 self._initial_centre = self._centre.copy()
96 greedy = self._new_actor(_seed(self._training_rng))
97 self._learner = _TD3Learner(greedy, self.td3, _seed(self._training_rng), self._counts)
98 self._strategy = None
99 self._arborescence = None
100 self._pending = None
101
102 def _build_actor(self, env, config, seed, device):
103 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
104
105 @property
106 def stats(self):
107 """Return cumulative counters and the number of transitions in replay."""
108 return CMAMEGATD3ESStats(**self._counts, replay_size=self._learner.replay.size)
109
110 @property
111 def centre(self):
112 """Return a copy of the current centre's flat parameters."""
113 return self._centre.copy()
114
115 def _reward_gradient(self):
116 if not self._counts["critic_updates"]:
117 return np.zeros_like(self._centre)
118 learner = self._learner
119 self._actor._set_parameters(self._centre)
120 observations = learner.replay.sample_observations(
121 self.gradient_batch_size, learner.sample_rng, self._actor.device)
122 predicted_return = _critic(learner.critics[0], observations, self._actor._normalized(observations)).mean()
123 gradients = torch.autograd.grad(predicted_return, self._actor._trainable_parameters())
124 gradient = torch.nn.utils.parameters_to_vector(gradients).detach().cpu().numpy()
125 if not np.isfinite(gradient).all():
126 raise ValueError("TD3 produced a nonfinite reward gradient.")
127 self._counts["reward_gradients"] += 1
128 return gradient
129
130 def _advance_centre(self, basis):
131 size = self.batch_size - 1
132 if self._strategy is None:
133 self._strategy = _strategy(np.zeros(len(basis)), self.sigma0, size, self._selection_rng)
134 coefficients = self._strategy.ask()
135 directions = np.asarray(coefficients) @ basis
136 ranks = []
137 for direction in directions:
138 _, rank = yield "branch", self._centre + direction
139 ranks.append(rank)
140 order = sorted(range(size), key=ranks.__getitem__, reverse=True)
141 self._strategy.tell(coefficients, _losses(order))
142 if ranks[order[0]][0] <= 0 or self._strategy.stop():
143 self._centre = (np.asarray(self._parent(), dtype=float) if self.archive
144 else self._initial_centre.copy())
145 self._strategy = None
146 self._counts["restarts"] += 1
147 return
148 selected = [i for i in order if ranks[i][0] >= 0][:self._strategy.sp.mu]
149 weights = self._strategy.sp.weights[:len(selected)]
150 self._centre += self.step_size * np.average(directions[selected], axis=0, weights=weights)
151
152 def _generation(self):
153 yield "centre", self._centre
154 noise = self._selection_rng.standard_normal((self.es_samples // 2, len(self._centre)))
155 positive, negative = [], []
156 for direction in self.es_sigma * noise:
157 descriptors, _ = yield "probe", self._centre + direction
158 positive.append(descriptors)
159 descriptors, _ = yield "probe", self._centre - direction
160 negative.append(descriptors)
161 measures = _rank_gradients(noise, positive, negative)
162 basis = _gradient_basis(np.vstack((self._reward_gradient(), measures)), 1.)
163 if np.any(basis):
164 yield from self._advance_centre(basis)
165 yield "greedy", self._learner.actor._parameters()
166 if self._learner.ready(self.stats.env_steps):
167 for _ in range(self.critic_steps):
168 self._learner.update()
169 self._counts["generations"] += 1
170
171 def _score(self, cursor, budget, phase, parameters):
172 probe = phase == "probe"
173 self._counts["perturbation_attempts" if probe else "candidate_attempts"] += 1
174 if phase == "greedy":
175 self._counts["actor_injections"] += 1
176 self._actor._set_parameters(parameters)
177 episodes = []
178 for _ in range(self._episodes):
179 episode = _evaluate_episode(cursor, self._actor, budget, self._learner.record,
180 phase="training_steps" if probe else "evaluation_steps")
181 if episode is None:
182 return None
183 episodes.append(episode)
184
185 values = [np.asarray(self._descriptor(episode), dtype=float) for episode in episodes]
186 dimension = len(self.archive.features_domain)
187 if any(row.shape != (dimension,) or not np.isfinite(row).all() for row in values):
188 raise ValueError(f"Expected finite descriptors of length {dimension}.")
189 descriptors = np.mean(values, axis=0)
190 if not np.isfinite(descriptors).all():
191 raise ValueError("The aggregated descriptors must be finite.")
192 if probe:
193 self._counts["completed_perturbations"] += 1
194 return descriptors, None
195
196 self._counts["evaluated_policies"] += 1
197 reward = float(np.mean([episode.return_ for episode in episodes]))
198 if not np.isfinite(reward):
199 raise ValueError("The mean episode return must be finite.")
200 rank = (-1, 0.)
201 if (self.archive.in_bounds(descriptors, self.archive.features_domain)
202 and self.archive.in_bounds((reward,), self.archive.fitness_domain)):
203 cell = self.archive.index_grid(descriptors)
204 front = self.archive.solutions[cell]
205 occupied = bool(front)
206 prior = self.archive.get_ind_fitness(front[0]).values[0] if occupied else 0.
207 admitted = self._offer((), phase, descriptors=[descriptors], quality=reward)
208 status = 1 if occupied else 2
209 rank = (status if admitted is not None else 0, reward - prior)
210 else:
211 self._counts["out_of_domain"] += 1
212 return descriptors, rank
213
214
215 def train(self, max_env_steps):
216 """Return cumulative stats. Retry interrupted policies with fresh resets.
217
218 An incomplete policy evaluation contributes its collected transitions
219 to replay. The pending proposal is retried on the next train call.
220 Only complete groups feed ES estimates, CMA ranks, or the archive.
221 """
222 budget = _StepBudget(max_env_steps, self._counts)
223 with _open_environment(self._factory) as env:
224 _check_spaces(env, self._actor)
225 cursor = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
226 while budget.remaining:
227 if self._arborescence is None:
228 self._arborescence = self._generation()
229 self._pending = next(self._arborescence)
230 phase, parameters = self._pending
231 measured = self._score(cursor, budget, phase, parameters)
232 if measured is None:
233 break
234 try:
235 self._pending = self._arborescence.send(measured)
236 except StopIteration:
237 self._arborescence = self._pending = None
238 if self._on_step is not None and phase != "probe":
239 self._on_step(self.archive, self.stats)
240 return self.stats
Environment costs and phase counts for CMA-MEGA (TD3, ES).
Definition cma_mega.py:24
Illuminate a continuous-control archive with TD3 and black-box measure gradients.
Definition cma_mega.py:40
_score(self, cursor, budget, phase, parameters)
Definition cma_mega.py:171
train(self, max_env_steps)
Spend an additional hard environment-step budget on the current arborescence.
Definition cma_mega.py:215
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
_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