41 """Implement the TD3 and ES variant of CMA-MEGA from Tjanaka et al.
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.
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.
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):
77 except ImportError
as error:
78 raise ImportError(
"CMAMEGATD3ES requires the CMA backend. Install qdpy[rl,cma].")
from error
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)
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.")
89 self.
critic_steps = _integer(critic_steps,
"critic_steps")
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)
102 def _build_actor(self, env, config, seed, device):
103 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
107 """Return cumulative counters and the number of transitions in replay."""
112 """Return a copy of the current centre's flat parameters."""
115 def _reward_gradient(self):
116 if not self.
_counts[
"critic_updates"]:
117 return np.zeros_like(self.
_centre)
120 observations = learner.replay.sample_observations(
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
130 def _advance_centre(self, basis):
135 directions = np.asarray(coefficients) @ basis
137 for direction
in directions:
138 _, rank =
yield "branch", self.
_centre + direction
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():
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)
152 def _generation(self):
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)
165 yield "greedy", self.
_learner.actor._parameters()
169 self.
_counts[
"generations"] += 1
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)
179 episode = _evaluate_episode(cursor, self.
_actor, budget, self.
_learner.record,
180 phase=
"training_steps" if probe
else "evaluation_steps")
183 episodes.append(episode)
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.")
193 self.
_counts[
"completed_perturbations"] += 1
194 return descriptors,
None
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.")
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)
211 self.
_counts[
"out_of_domain"] += 1
212 return descriptors, rank
216 """Return cumulative stats. Retry interrupted policies with fresh resets.
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.
223 with _open_environment(self.
_factory)
as env:
224 _check_spaces(env, self.
_actor)
226 while budget.remaining:
231 measured = self.
_score(cursor, budget, phase, parameters)
236 except StopIteration:
238 if self.
_on_step is not None and phase !=
"probe":