35 """Adapt Lim, Flageat and Cully's GDA-QD to synchronous Gymnasium rollouts.
37 Each model cycle starts with a copy of the verified archive. Select
38 new or improved imagined elites and reserve a fraction for gradients
39 from a TD3 critic. The gradients use replay from the real environment.
40 Both branches receive complete real evaluations for archive admission.
41 The model trains on direct transfers and warm-up data by default.
43 :param env_factory: Factory for a continuous Gymnasium environment.
44 :param archive: Empty best-only Grid or CVTGrid.
45 :param td3: Optional TD3Config for the separate critic replay and targets.
46 :param gradient_fraction: Target fraction of selected transfers to
47 mutate with policy gradients. Zero runs the seeded model-only control.
48 :param critic_steps: TD3 minibatch updates per ready model cycle.
49 :param pg_steps: Adam updates per gradient-mutated transfer.
50 :param pg_learning_rate: Positive learning rate for gradient mutation.
51 :param exclude_gradient_from_model: Exclude gradient-policy transitions
52 from dynamics fitting, as in the paper. The critic sees both sources.
53 :param kwargs: DynamicsAwareQD settings, including descriptor and model_reward.
56 def __init__(self, env_factory, archive, *, td3=None, gradient_fraction=.1, critic_steps=8,
57 pg_steps=4, pg_learning_rate=1e-3, exclude_gradient_from_model=True, **kwargs):
58 if not (0 <= gradient_fraction <= 1
and 0 < pg_learning_rate < np.inf):
59 raise ValueError(
"Use gradient_fraction in [0, 1] and a finite positive pg_learning_rate.")
60 if type(exclude_gradient_from_model)
is not bool:
61 raise TypeError(
"exclude_gradient_from_model must be a bool.")
63 if not isinstance(td3, TD3Config):
64 raise TypeError(
"td3 must be a TD3Config.")
66 self.
_pg_steps = _integer(pg_steps,
"pg_steps")
69 super().__init__(env_factory, archive, **kwargs)
72 seed = kwargs.get(
"seed", 0)
73 self.
_gradient_rng = np.random.default_rng(np.random.SeedSequence(seed, spawn_key=(4,)))
75 if gradient_fraction > 0:
84 """Report cumulative stats and separate replay occupancy."""
86 critic_replay_size=0
if self.
_learner is None else self.
_learner.replay.size)
88 def _observe(self, obs, action, reward, successor, terminated):
90 super()._observe(obs, action, reward, successor, terminated)
92 self.
_learner.record(obs, action, reward, successor, terminated)
94 def _model_search(self):
97 initial = {grid.index_grid(individual): (grid.get_ind_fitness(individual).values[0],
98 0., np.asarray(individual, dtype=np.float32))
99 for individual
in grid}
101 changes = [entry
for cell, entry
in imagined.items()
if entry
is not initial.get(cell)]
102 changes.sort(key=
lambda entry: (entry[1], -entry[0]))
114 gradients.update(self.
_gradient_rng.choice(len(vectors), count, replace=
False).tolist())
115 for slot, vector
in enumerate(vectors):
116 if slot
in gradients:
117 self.
_actor._set_parameters(vector)
123 def _next_candidate(self):
127 emitter, vector = super()._next_candidate()
129 return emitter, vector
131 def _record_transfer(self, emitter):
132 super()._record_transfer(emitter)
133 if emitter ==
"gradient_transfer":
134 self.
_counts[
"gradient_transfers"] += 1