QDpy
Loading...
Searching...
No Matches
gda_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Gradient-assisted Dynamics-Aware QD for bounded continuous policies."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from .dynamics_aware import DynamicsAwareQD, DynamicsAwareQDStats
13from .policy import _integer
14from .rollout import _seed
15from .td3 import TD3Config, _TD3Learner
16
17__all__ = ["GDAQD", "GDAQDStats"]
18
19
20
21@dataclass(frozen=True)
23 """Report completed transfers, TD3 updates, and both real replay buffers."""
24
25 gradient_transfers: int = 0
26 critic_updates: int = 0
27 actor_updates: int = 0
28 policy_gradient_steps: int = 0
29 model_replay_size: int = 0
30 critic_replay_size: int = 0
31
32
33
35 """Adapt Lim, Flageat and Cully's GDA-QD to synchronous Gymnasium rollouts.
36
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.
42
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.
54 """
55
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.")
62 td3 = TD3Config() if td3 is None else td3
63 if not isinstance(td3, TD3Config):
64 raise TypeError("td3 must be a TD3Config.")
65 self._critic_steps = _integer(critic_steps, "critic_steps")
66 self._pg_steps = _integer(pg_steps, "pg_steps")
67 self._pg_rate, self._gradient_fraction = pg_learning_rate, gradient_fraction
68 self._exclude_gradient = exclude_gradient_from_model
69 super().__init__(env_factory, archive, **kwargs)
70 # Derive an independent stream without consuming the inherited
71 # dynamics RNG. The seeded model-only control can match model draws.
72 seed = kwargs.get("seed", 0)
73 self._gradient_rng = np.random.default_rng(np.random.SeedSequence(seed, spawn_key=(4,)))
74 self._learner = None
75 if gradient_fraction > 0:
76 greedy = self._new_actor(_seed(self._gradient_rng))
77 self._learner = _TD3Learner(greedy, td3, _seed(self._gradient_rng), self._counts)
78 self._gradient_credit = 0.
79 self._current_emitter = "genetic"
80
81
82 @property
83 def stats(self):
84 """Report cumulative stats and separate replay occupancy."""
85 return GDAQDStats(**self._counts, model_replay_size=self._replay.size,
86 critic_replay_size=0 if self._learner is None else self._learner.replay.size)
87
88 def _observe(self, obs, action, reward, successor, terminated):
89 if not self._exclude_gradient or self._current_emitter != "gradient_transfer":
90 super()._observe(obs, action, reward, successor, terminated)
91 if self._learner is not None:
92 self._learner.record(obs, action, reward, successor, terminated)
93
94 def _model_search(self):
95 self._fit_dynamics()
96 grid = self.archive
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}
100 imagined = self._illuminate_model(initial)
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]))
103 vectors = [entry[2] for entry in changes[:self._max_transfers]]
104
105 gradients = set()
106 if vectors and self._learner is not None and self._learner.ready(self._counts["evaluation_steps"]):
107 for _ in range(self._critic_steps):
108 self._learner.update()
109 # Keep fractional slots between successful cycles so a small
110 # transfer batch still uses the requested proportion over time.
111 self._gradient_credit += self._gradient_fraction * len(vectors)
112 count = min(len(vectors), int(self._gradient_credit + 1e-12))
113 self._gradient_credit = max(0., self._gradient_credit - count)
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)
118 self._learner.improve_offspring(self._actor, self._pg_steps, self._pg_rate)
119 self._transfers.append(("gradient_transfer", self._actor._parameters()))
120 else:
121 self._transfers.append(("transfer", vector))
122
123 def _next_candidate(self):
124 if self._transfers:
125 emitter, vector = self._transfers.popleft()
126 else:
127 emitter, vector = super()._next_candidate()
128 self._current_emitter = emitter
129 return emitter, vector
130
131 def _record_transfer(self, emitter):
132 super()._record_transfer(emitter)
133 if emitter == "gradient_transfer":
134 self._counts["gradient_transfers"] += 1
Distinguish model work from actual environment calls in Dynamics-Aware QD.
Discover policies with an imagined repertoire and verify them in the environment.
Count TD3 work and real evaluations alongside imagined transitions.
Definition gda_qd.py:22
Illuminate an imagined archive, then improve a subset using real-data TD3 gradients.
Definition gda_qd.py:34
stats(self)
Return costs for model rollouts, true evaluations, and TD3.
Definition gda_qd.py:83
_new_actor(self, seed, device=None)
Definition search.py:112
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25