23 """Predict diagonal Gaussian observation deltas with bootstrapped likelihood fits."""
25 def __init__(self, obs_size, action_size, count, config, actor, rng, learning_rate):
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)
32 def _predictions(network, inputs):
33 mean, log_variance = network(inputs).chunk(2, dim=-1)
34 return mean, log_variance.clamp(-10., 3.)
36 def fit(self, replay, batch_size, rng):
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)
50 def predict(self, observation, action, rng=None):
51 inputs = self.
actor._tensor(np.concatenate((observation, self.
actor._encode(action))))
53 deltas = torch.stack([mean
for mean, _
in predictions]).cpu().numpy().astype(float)
55 delta = deltas.mean(axis=0)
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())
77 """Dynamics-Aware QD following Lim et al. (ICRA 2022).
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.
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.
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)
125 raise ValueError(
"replay_capacity must cover min_model_steps.")
128 self.
_imagined = _integer(imagined_candidates,
"imagined_candidates")
130 self.
_max_transfers =
None if max_transfers
is None else _integer(max_transfers,
"max_transfers")
132 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
133 obs_size, action_size = prod(self.
_actor._obs_shape), prod(self.
_actor._actions.shape)
135 self.
_starts = deque(maxlen=min(capacity, 256))
137 config =
PolicyConfig((64, 64))
if model_policy
is None else model_policy
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.")
149 """Return cumulative real and imagined evaluation costs."""
152 def _observe(self, obs, action, reward, successor, terminated):
153 self.
_replay.add(obs, self.
_actor._encode(action), reward, successor, terminated)
159 def _dream_from(self, start):
160 shape = self.
_actor._obs_shape
161 states, actions, rewards, uncertainties = [start], [], [], []
165 action = self.
_actor._greedy(obs)
167 nxt, uncertainty = self.
_model.predict(obs, action, rng)
168 args = obs.reshape(shape), action, nxt.reshape(shape)
170 if not np.isfinite(reward):
171 raise ValueError(
"model_reward must return a finite scalar.")
174 actions.append(action)
175 rewards.append(reward)
176 uncertainties.append(uncertainty)
177 self.
_counts[
"imagined_steps"] += 1
180 episode =
Episode(np.stack(states).reshape(-1, *shape), tuple(actions), tuple(rewards),
181 {}, {}, terminated,
not terminated)
182 return episode, np.mean(uncertainties)
184 def _dream_score(self):
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))
198 def _fit_dynamics(self):
201 self.
_counts[
"model_updates"] += updates
202 self.
_counts[
"optimizer_steps"] += updates
204 def _illuminate_model(self, initial):
205 imagined = initial.copy()
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,
214 self.
_actor._set_parameters(vector)
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)):
220 cell = self.
archive.index_grid(features)
221 if cell
not in imagined
or score > imagined[cell][0]:
222 imagined[cell] = score, disagreement, vector
225 def _model_search(self):
228 ranked = sorted(imagined.values(), key=
lambda entry: (entry[1], -entry[0]))
231 def _next_candidate(self):
236 def _record_transfer(self, emitter):
237 self.
_counts[
"transferred_policies"] += 1
241 """Return cumulative statistics, retaining queued transfers for the next call."""
244 if budget.remaining >= candidate_limit:
245 with _open_environment(self.
_factory)
as env:
246 _check_spaces(env, self.
_actor)
248 while budget.remaining >= candidate_limit:
253 self.
_actor._set_parameters(vector)
254 self.
_counts[
"candidate_attempts"] += 1
255 episodes = [_evaluate_episode(cursor, self.
_actor, budget, self.
_observe)
257 self.
_starts.extend(episode.observations[0].reshape(-1).copy()
for episode
in episodes)
258 self.
_counts[
"evaluated_policies"] += 1
259 if emitter !=
"genetic":
261 self.
_offer(episodes, emitter)