20from .td3
import TD3Config, _Replay, _checked_step, _critic_loss, _polyak, _step_actor, _td3_targets, _twin_critics
48 """A FIFO ring of state descriptors admitted by a strict mean-kNN threshold."""
50 def __init__(self, capacity, dimension, neighbors, threshold, metric):
51 self.
data = np.empty((capacity, dimension), dtype=np.float64)
53 self.
metric = cdist
if metric
is None else metric
54 self.
size = self.admissions = 0
57 def score(self, descriptors):
59 return np.zeros(len(descriptors), dtype=np.float64)
60 points = self.
data[:self.
size].view()
61 points.flags.writeable =
False
62 distances = np.asarray(self.
metric(descriptors, points), dtype=np.float64)
63 if (distances.shape != (len(descriptors), self.
size)
or not np.isfinite(distances).all()
64 or np.any(distances < 0)):
65 raise ValueError(
"novelty_metric must return a finite, nonnegative distance matrix.")
67 closest = np.partition(distances, k - 1, axis=1)[:, :k]
68 return np.sum(closest / k, axis=1)
71 """Reuse an exact index during replay when the Euclidean workload is small-dimensional."""
72 if not (self.
metric is cdist
and self.
size >= 512
and self.
data.shape[1] <= 8
73 and self.
neighbors <= 32
and len(descriptors) > 1):
74 return self.
score(descriptors)
77 if np.any(np.abs(descriptors) > limit):
78 return self.
score(descriptors)
81 if np.any(np.abs(points) > limit):
82 return self.
score(descriptors)
83 self.
_index = cKDTree(points, copy_data=
True)
84 distances = self.
_index.query(descriptors, k=list(range(1, self.
neighbors + 1)))[0]
85 return np.sum(distances / self.
neighbors, axis=1)
87 def add(self, descriptor):
91 self.
data[self.admissions % len(self.
data)] = descriptor
93 self.
size = min(self.admissions, len(self.
data))
97 """Store the pre-action descriptor in the same row as its transition."""
99 def __init__(self, capacity, actor, dimension):
100 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
101 self.
descriptors = np.empty((capacity, dimension), dtype=np.float64)
104 def add_transition(self, observation, action, reward, successor, terminated, descriptor):
106 self.
add(observation, self.
actor._encode(action), reward, successor, terminated)
120 """Share one independently trained TD3 critic pair across a half-generation."""
122 def __init__(self, actor, config, rng):
124 self.
device = actor.device
126 self.
noise_rng = torch.Generator(device=self.
device).manual_seed(_seed(rng))
127 self.
critics = _twin_critics(actor, config, rng, rng)
129 self.
optimizer = torch.optim.SGD(self.
critics.parameters(), lr=config.critic_learning_rate)
132 def prepare(self, actor):
134 actor, deepcopy(actor._network).requires_grad_(
False),
135 torch.optim.SGD(actor._trainable_parameters(), lr=self.
config.actor_learning_rate),
138 def _sample(self, replay, novelty):
139 rows = self.
rng.integers(replay.size, size=self.
config.batch_size)
140 observations, actions, rewards, successors, terminated = replay.batch(rows, self.
device)
141 if novelty
is not None:
142 scores = novelty.replay_score(replay.descriptors[rows])
143 if not np.isfinite(scores).all()
or np.any(scores > np.finfo(np.float32).max):
144 raise ValueError(
"QD-PG requires diversity rewards representable in float32.")
145 rewards = torch.as_tensor(scores, dtype=rewards.dtype, device=self.
device)
146 return observations, actions, rewards, successors, terminated
148 def update(self, candidates, replay, novelty):
149 """Average the critic gradients, then apply the delayed actor and target updates."""
150 self.
optimizer.zero_grad(set_to_none=
True)
152 for candidate
in candidates:
153 observations, actions, rewards, successors, terminated = self.
_sample(replay, novelty)
155 actions, rewards, successors, terminated)
156 loss = _critic_loss(self.
critics, observations, actions, target)
157 (loss / len(candidates)).backward()
158 actor_batches.append(observations)
164 for candidate, observations
in zip(candidates, actor_batches):
165 _step_actor(candidate.actor, candidate.optimizer, self.
critics[0], observations)
166 self.actor_updates += 1
167 _polyak(candidate.actor._network, candidate.target, self.
config.tau)
173 """Train half the generation toward task return and half toward state novelty.
175 Each objective has a separate pair of shared critics. The algorithm
176 clones elites, fits both critic pairs on a single shared replay buffer,
177 and varies each clone with its assigned gradient. It evaluates every
178 proposal in the environment. Episode descriptors select archive cells,
179 and raw episodic return or the supplied fitness ranks the candidates.
181 :param env_factory: Factory for a single Gymnasium environment with bounded
182 floating-point Box actions.
183 :param archive: Best-only QDpy Grid or CVTGrid as in :class:`NeuralMAPElites`.
184 :param state_descriptor: Callable taking the pre-action non-flattened
185 float32 observation and its reset or step info. Return a finite 1-D
186 vector with the same number of coordinates as the episode descriptor.
187 Use state coordinates that have a meaningful relation to the episode
188 descriptor, such as current position and final position.
189 :param td3: Optional :class:`TD3Config` for the replay and twin critics.
190 QD-PG uses SGD and draws replay batches with replacement.
191 ``learning_starts`` can extend the random-policy warmup.
192 :param population_size: Even number of proposals per generation. Unless
193 overridden, also the number of initial random policies.
194 :param gradient_steps_ratio: Optimizer rounds per objective are the floor
195 of this ratio times the number of transitions collected since the
196 start of the previous generation.
197 :param novelty_capacity: Maximum number of admitted timestep descriptors.
198 :param novelty_neighbors: Number of nearest neighbors used in the mean.
199 :param novelty_threshold: An arrival must score strictly above this
200 threshold to enter the novelty archive. The first arrival is accepted.
201 :param novelty_metric: Optional pairwise distance function. Takes query
202 rows and archive rows, and returns a nonnegative (queries, archive)
203 distance matrix. Defaults to Euclidean distance.
204 :param kwargs: Evaluation and policy options for :class:`NeuralMAPElites`.
207 def __init__(self, env_factory, archive, *, descriptor, state_descriptor, td3=None,
208 population_size=4, initial_policies=None, gradient_steps_ratio=0.25,
209 novelty_capacity=10_000, novelty_neighbors=10, novelty_threshold=0.01,
210 novelty_metric=None, **kwargs):
211 if not callable(state_descriptor):
212 raise TypeError(
"state_descriptor must be callable.")
213 if novelty_metric
is not None and not callable(novelty_metric):
214 raise TypeError(
"novelty_metric must be callable.")
217 raise ValueError(
"population_size must be even.")
218 if not isfinite(gradient_steps_ratio)
or gradient_steps_ratio <= 0:
219 raise ValueError(
"gradient_steps_ratio must be finite and positive.")
220 if not isfinite(novelty_threshold)
or novelty_threshold < 0:
221 raise ValueError(
"novelty_threshold must be finite and nonnegative.")
223 self.
td3 = (
TD3Config(learning_starts=0, batch_size=64, critic_hidden_sizes=(64, 32),
224 actor_learning_rate=0.003, critic_learning_rate=0.003)
225 if td3
is None else td3)
226 if not isinstance(self.
td3, TD3Config):
227 raise TypeError(
"td3 must be a TD3Config.")
228 capacity = _integer(novelty_capacity,
"novelty_capacity")
229 neighbors = _integer(novelty_neighbors,
"novelty_neighbors")
230 initial = self.
population_size if initial_policies
is None else initial_policies
231 super().__init__(env_factory, archive, descriptor=descriptor, initial_policies=initial, **kwargs)
233 dimension = len(archive.features_domain)
243 def _build_actor(self, env, config, seed, device):
244 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
248 """Return cumulative training costs, operator counts, and buffer sizes."""
251 return QDPGStats(**self.
_counts, critic_updates=critic_updates, policy_gradient_steps=actor_updates,
252 optimizer_steps=critic_updates + actor_updates, replay_size=self.
_replay.size,
253 novelty_size=self.
_novelty.size, novelty_admissions=self.
_novelty.admissions)
255 def _state_descriptor(self, observation, info):
256 value = np.array(self.
_describe_state(observation.copy(), deepcopy(dict(info))), dtype=np.float64, copy=
True)
257 dimension = len(self.
archive.features_domain)
258 if value.shape != (dimension,)
or not np.isfinite(value).all():
259 raise ValueError(f
"Expected a finite state descriptor of length {dimension}.")
262 def _transition(self, observation, action, reward, successor, terminated, descriptor):
263 self.
_replay.add_transition(observation, action, reward, successor, terminated, descriptor)
266 def _prepare(self, cursor, budget):
273 self.
_actor._set_parameters(parameters)
274 self.
_counts[f
"{objective}_offspring"] += 1
277 def _build_generation(self):
278 steps = self.
_counts[
"evaluation_steps"]
281 for name, objective, novelty
in (
287 candidates.append(objective.prepare(actor))
288 for _
in range(rounds):
289 objective.update(candidates, self.
_replay, novelty)
290 generation.extend((name, candidate.actor._parameters())
for candidate
in candidates)