73 """Hold both episode labels and raw TD3 data in the same FIFO rows."""
75 def __init__(self, capacity, actor, dimension, length_scale):
76 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
78 self.
achieved = np.empty((capacity, dimension), dtype=np.float32)
80 self.
operators = np.empty(capacity, dtype=np.uint8)
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.")
92 start = max(0, count - self.
capacity)
94 observations = episode.observations.reshape(count + 1, -1)
95 actions = np.asarray(episode.actions, dtype=np.float64).reshape(count, -1)[start:]
99 self.
rewards[rows] = rewards[start:]
101 self.
terminated[rows[-1]] = episode.terminated
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)
116 """Share the conditioned learner, scoring, and budget across DCG and DCRL."""
118 _pg_target_in_replay =
False
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):
123 if not isinstance(self.
td3, TD3Config):
124 raise TypeError(
"td3 must be a TD3Config.")
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.")
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)
140 self.
_conditioned = DescriptorConditionedPolicy._from_layout(
148 def _make_learner(self, length_scale):
153 def _build_actor(self, env, config, seed, device):
154 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
158 """Return cumulative budgets, completed evaluations, and replay size."""
163 """Return an actor that accepts a target descriptor in physical units."""
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,
169 copy._model._set_parameters(model._parameters())
172 def _improve(self, parent, goal):
174 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=self.
pg_learning_rate)
176 target = actor._tensor(goal)
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
185 def _train_learner(self):
189 def _build_generation(self):
195 proposals.append(self.
_improve(parent, self.
_domain.normalize(parent.features.values, goal=
True)))
196 return self._add_actor_proposals(proposals)
198 def _prepare_proposal(self):
200 steps = self.
_counts[
"evaluation_steps"] + self.
_counts[
"training_steps"]
208 """Continue the search and keep unstarted proposals queued across calls."""
210 with _open_environment(self.
_factory)
as env:
211 _check_spaces(env, self.
_actor)
214 while budget.remaining:
219 def _collect_episode(self, cursor, budget, phase, proposal):
220 episode = _evaluate_episode(cursor, self.
_actor, budget, phase=phase)
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
227 def _evaluate_proposal(self, proposal, evaluation, collection, budget):
228 operator = proposal.operator
229 auxiliary = operator == _Operator.ACTOR_EVALUATION
231 self.
_counts[
"actor_evaluation_attempts"] += 1
233 self.
_counts[
"candidate_attempts"] += 1
234 key = _OFFSPRING_COUNTERS.get(operator)
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
246 self.
_counts[
"unlabeled_steps"] += before - budget.remaining
248 episodes.append(episode)
249 descriptors.append(achieved)
251 self.
_counts[
"actor_evaluations"] += 1
254 self.
_counts[
"evaluated_policies"] += 1
255 self.
_offer(episodes, operator.name.lower(), descriptors=descriptors)
262 """Implement the GECCO 2023 replay and offspring schedule.
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.
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.
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):
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)
298 if not isfinite(goal_noise)
or goal_noise < 0:
299 raise ValueError(
"goal_noise must be finite and nonnegative.")
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)
305 def _add_actor_proposals(self, proposals):
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)
311 active.append(
_Proposal(_Operator.ACTOR_EVALUATION, actor._parameters(), goal))
312 return active + proposals
317 """Implement the actor-injection schedule from the 2024 DCRL paper.
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.
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.
333 _pg_target_in_replay =
True
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):
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)
343 def _add_actor_proposals(self, proposals):
345 goal = self.
_goals.uniform(-1, 1, size=len(self.
_domain.bounds)).astype(np.float32)
347 proposals.append(
_Proposal(_Operator.INJECTION, actor._parameters(), goal))