QDpy
Loading...
Searching...
No Matches
dynamics_aware.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Dynamics-Aware QD for continuous Gymnasium environments."""
6
7from collections import deque
8from dataclasses import dataclass
9from math import prod
10
11import numpy as np
12import torch
13
14from qdpy.tools import iso_line_dd
15from .policy import PolicyConfig, _BoxLayout, _integer, _mlp
16from .rollout import Episode, TrainingStats, _Cursor, _StepBudget, _check_spaces, _evaluate_episode
17from .rollout import _open_environment, _seed
18from .search import NeuralMAPElites
19from .td3 import _Replay
20
21
23 """Predict diagonal Gaussian observation deltas with bootstrapped likelihood fits."""
24
25 def __init__(self, obs_size, action_size, count, config, actor, rng, learning_rate):
26 self.actor = actor
27 self.networks = tuple(_mlp(obs_size + action_size, 2 * obs_size, config, _seed(rng),
28 actor.device, torch.nn.SiLU) for _ in range(count))
29 self.optimizers = tuple(torch.optim.Adam(net.parameters(), lr=learning_rate) for net in self.networks)
30
31 @staticmethod
32 def _predictions(network, inputs):
33 mean, log_variance = network(inputs).chunk(2, dim=-1)
34 return mean, log_variance.clamp(-10., 3.)
35
36 def fit(self, replay, batch_size, rng):
37 for network, optimizer in zip(self.networks, self.optimizers):
38 observations, actions, _, successors, _ = replay.sample(batch_size, rng, self.actor.device)
39 mean, log_variance = self._predictions(network, torch.cat((observations, actions), dim=-1))
40 error = successors - observations - mean
41 loss = 0.5 * (log_variance + error.square() * (-log_variance).exp()).mean()
42 if not torch.isfinite(loss):
43 raise ValueError("The dynamics ensemble produced a nonfinite loss.")
44 optimizer.zero_grad(set_to_none=True)
45 loss.backward()
46 optimizer.step()
47 return len(self.networks)
48
49 @torch.no_grad()
50 def predict(self, observation, action, rng=None):
51 inputs = self.actor._tensor(np.concatenate((observation, self.actor._encode(action))))
52 predictions = [self._predictions(net, inputs) for net in self.networks]
53 deltas = torch.stack([mean for mean, _ in predictions]).cpu().numpy().astype(float)
54 if rng is None:
55 delta = deltas.mean(axis=0)
56 else:
57 index = rng.integers(len(deltas))
58 deviation = (0.5 * predictions[index][1]).exp().cpu().numpy()
59 delta = deltas[index] + deviation * rng.standard_normal(len(observation))
60 successor = self.actor._observation((observation + delta).reshape(self.actor._obs_shape))
61 return successor, float(deltas.std(axis=0).mean())
62
63
64
65@dataclass(frozen=True)
67 """Add model updates, imagined policies and transitions, and completed transfers."""
68
69 model_updates: int = 0
70 imagined_policies: int = 0
71 imagined_steps: int = 0
72 transferred_policies: int = 0
73
74
75
77 """Dynamics-Aware QD following Lim et al. (ICRA 2022).
78
79 Real evaluations of all policies supply transition data for the
80 dynamics ensemble. Each model-search cycle evaluates its candidates
81 with ensemble-mean rollouts and builds a separate imagined repertoire.
82 A subset of that repertoire is transferred for true evaluation.
83
84 :param env_factory: Factory for a continuous Gymnasium environment.
85 :param archive: Empty best-only Grid or CVTGrid for verified policies.
86 :param descriptor: Function of a completed real or imagined Episode.
87 Imagined episodes have empty info mappings.
88 :param model_reward: Compute an imagined reward from the observation,
89 physical action, and successor, all in environment coordinates.
90 :param model_terminated: Optional function of the same inputs to stop
91 imagined episodes early. Otherwise they run to max_episode_steps.
92 :param ensemble_size: Number of Gaussian transition models, at least two.
93 :param model_policy: Optional PolicyConfig for transition-network widths.
94 :param model_learning_rate: Positive Adam learning rate.
95 :param model_updates: Minibatch updates per member before each imagined cycle.
96 :param model_batch_size: Random replay samples per member update.
97 :param min_model_steps: Minimum number of true transitions in replay before model fitting.
98 :param replay_capacity: Maximum number of observed transitions in replay.
99 :param imagined_candidates: Number of model-scored proposals per cycle.
100 :param sample_dynamics: Sample a model and its predicted Gaussian at
101 each imagined step. By default use the ensemble mean.
102 :param max_transfers: Limit on true evaluations from each imagined repertoire,
103 ordered by increasing model disagreement. None transfers all.
104 :param kwargs: NeuralMAPElites policy, fitness, budget horizon, warm-up,
105 evaluation episodes, optional callback, and seeding settings.
106 """
107
108 def __init__(self, env_factory, archive, *, descriptor, model_reward, model_terminated=None,
109 ensemble_size=3, model_policy=None, model_learning_rate=1e-3,
110 model_updates=16, model_batch_size=64, min_model_steps=64,
111 replay_capacity=50_000, imagined_candidates=32, max_transfers=4,
112 sample_dynamics=False, **kwargs):
113 if not callable(model_reward) or (model_terminated is not None and not callable(model_terminated)):
114 raise TypeError("model_reward and model_terminated must be callable when supplied.")
115 if model_policy is not None and not isinstance(model_policy, PolicyConfig):
116 raise TypeError("model_policy must be a PolicyConfig.")
117 if not 0 < model_learning_rate < np.inf:
118 raise ValueError("model_learning_rate must be finite and positive.")
119 if type(sample_dynamics) is not bool:
120 raise TypeError("sample_dynamics must be a bool.")
121 capacity = _integer(replay_capacity, "replay_capacity")
122 count = _integer(ensemble_size, "ensemble_size", 2)
123 self._min_model_steps = _integer(min_model_steps, "min_model_steps")
124 if self._min_model_steps > capacity:
125 raise ValueError("replay_capacity must cover min_model_steps.")
126 self._model_updates = _integer(model_updates, "model_updates")
127 self._model_batch_size = _integer(model_batch_size, "model_batch_size")
128 self._imagined = _integer(imagined_candidates, "imagined_candidates")
129 self._sample_dynamics = sample_dynamics
130 self._max_transfers = None if max_transfers is None else _integer(max_transfers, "max_transfers")
131 self._model_reward, self._model_terminated = model_reward, model_terminated
132 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
133 obs_size, action_size = prod(self._actor._obs_shape), prod(self._actor._actions.shape)
134 self._replay = _Replay(capacity, obs_size, action_size)
135 self._starts = deque(maxlen=min(capacity, 256))
136 self._transfers = deque()
137 config = PolicyConfig((64, 64)) if model_policy is None else model_policy
138 self._model = _DynamicsEnsemble(obs_size, action_size, count, config, self._actor,
139 self._training_rng, model_learning_rate)
140
141 def _build_actor(self, env, config, seed, device):
142 actor = super()._build_actor(env, config, seed, device)
143 if not isinstance(actor._actions, _BoxLayout):
144 raise ValueError("DynamicsAwareQD requires a bounded floating-point Box action space.")
145 return actor
146
147 @property
148 def stats(self):
149 """Return cumulative real and imagined evaluation costs."""
150 return DynamicsAwareQDStats(**self._counts)
151
152 def _observe(self, obs, action, reward, successor, terminated):
153 self._replay.add(obs, self._actor._encode(action), reward, successor, terminated)
154
155 def _dream(self):
156 start = self._starts[int(self._training_rng.integers(len(self._starts)))]
157 return self._dream_from(start)
158
159 def _dream_from(self, start):
160 shape = self._actor._obs_shape
161 states, actions, rewards, uncertainties = [start], [], [], []
162 terminated = False
163 for _ in range(self._horizon):
164 obs = states[-1]
165 action = self._actor._greedy(obs)
166 rng = self._training_rng if self._sample_dynamics else None
167 nxt, uncertainty = self._model.predict(obs, action, rng)
168 args = obs.reshape(shape), action, nxt.reshape(shape)
169 reward = float(self._model_reward(*args))
170 if not np.isfinite(reward):
171 raise ValueError("model_reward must return a finite scalar.")
172 terminated = self._model_terminated is not None and bool(self._model_terminated(*args))
173 states.append(nxt)
174 actions.append(action)
175 rewards.append(reward)
176 uncertainties.append(uncertainty)
177 self._counts["imagined_steps"] += 1
178 if terminated:
179 break
180 episode = Episode(np.stack(states).reshape(-1, *shape), tuple(actions), tuple(rewards),
181 {}, {}, terminated, not terminated)
182 return episode, np.mean(uncertainties)
183
184 def _dream_score(self):
185 return self._score_dreams([self._dream() for _ in range(self._episodes)])
186
187 def _score_dreams(self, dreams):
188 episodes, uncertainty = zip(*dreams)
189 scores = np.asarray([episode.return_ if self._fitness is None else self._fitness(episode)
190 for episode in episodes], dtype=float)
191 features = np.asarray([self._descriptor(episode) for episode in episodes], dtype=float)
192 if (features.shape != (len(dreams), len(self.archive.features_domain))
193 or scores.shape != (len(dreams),) or not np.isfinite(features).all()
194 or not np.isfinite(scores).all()):
195 raise ValueError("Imagined episodes require finite scalar fitness and matching finite descriptors.")
196 return float(scores.mean()), tuple(features.mean(axis=0)), float(np.mean(uncertainty))
197
198 def _fit_dynamics(self):
199 for _ in range(self._model_updates):
200 updates = self._model.fit(self._replay, self._model_batch_size, self._training_rng)
201 self._counts["model_updates"] += updates
202 self._counts["optimizer_steps"] += updates
203
204 def _illuminate_model(self, initial):
205 imagined = initial.copy()
206 for _ in range(self._imagined):
207 if imagined:
208 parents = tuple(imagined.values())
209 first, second = self._selection_rng.integers(len(parents), size=2)
210 vector = iso_line_dd(parents[first][2], parents[second][2], iso_sigma=self._iso_sigma,
211 line_sigma=self._line_sigma, rng=self._selection_rng)
212 else:
213 vector = self._genetic_parameters()
214 self._actor._set_parameters(vector)
215 score, features, disagreement = self._dream_score()
216 self._counts["imagined_policies"] += 1
217 if not (self.archive.in_bounds(features, self.archive.features_domain)
218 and self.archive.in_bounds((score,), self.archive.fitness_domain)):
219 continue
220 cell = self.archive.index_grid(features)
221 if cell not in imagined or score > imagined[cell][0]:
222 imagined[cell] = score, disagreement, vector
223 return imagined
224
225 def _model_search(self):
226 self._fit_dynamics()
227 imagined = self._illuminate_model({})
228 ranked = sorted(imagined.values(), key=lambda entry: (entry[1], -entry[0]))
229 self._transfers.extend(entry[2] for entry in ranked[:self._max_transfers])
230
231 def _next_candidate(self):
232 if self._transfers:
233 return "transfer", self._transfers.popleft()
234 return "genetic", self._genetic_parameters()
235
236 def _record_transfer(self, emitter):
237 self._counts["transferred_policies"] += 1
238
239
240 def train(self, max_env_steps):
241 """Return cumulative statistics, retaining queued transfers for the next call."""
242 budget = _StepBudget(max_env_steps, self._counts)
243 candidate_limit = self._episodes * self._horizon
244 if budget.remaining >= candidate_limit:
245 with _open_environment(self._factory) as env:
246 _check_spaces(env, self._actor)
247 cursor = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
248 while budget.remaining >= candidate_limit:
249 if (not self._transfers and self._replay.size >= self._min_model_steps
250 and self._counts["evaluated_policies"] >= self._initial_policies):
251 self._model_search()
252 emitter, vector = self._next_candidate()
253 self._actor._set_parameters(vector)
254 self._counts["candidate_attempts"] += 1
255 episodes = [_evaluate_episode(cursor, self._actor, budget, self._observe)
256 for _ in range(self._episodes)]
257 self._starts.extend(episode.observations[0].reshape(-1).copy() for episode in episodes)
258 self._counts["evaluated_policies"] += 1
259 if emitter != "genetic":
260 self._record_transfer(emitter)
261 self._offer(episodes, emitter)
262 if self._on_step is not None:
263 self._on_step(self.archive, self.stats)
264 return self.stats
Distinguish model work from actual environment calls in Dynamics-Aware QD.
Discover policies with an imagined repertoire and verify them in the environment.
_observe(self, obs, action, reward, successor, terminated)
train(self, max_env_steps)
Spend the environment budget on complete true evaluations and collect transition replay.
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Measurements from a completed evaluation episode.
Definition rollout.py:20
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Definition search.py:24
_offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None)
Definition search.py:119