QDpy
Loading...
Searching...
No Matches
ppga.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Synchronous PyTorch PPGA with separate search and reporting archives."""
6
7from copy import deepcopy
8from dataclasses import dataclass
9
10import numpy as np
11
12from qdpy.algorithms.differentiable import _gradient_basis
13from .policy import _BoxLayout, _integer
14from .ppo import PPOConfig, _Learner
15from .rollout import TrainingStats, _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
16from .search import NeuralMAPElites
17
18
19class _XNES:
20 """Exponential NES using centered rank utilities and an implicit covariance."""
21
22 def __init__(self, dimension, sigma):
23 self.mean = np.zeros(dimension)
24 self.transform = np.eye(dimension) * sigma
25 self.rate = 0.6 * (3 + np.log(dimension)) / (dimension * np.sqrt(dimension))
26
27 def sample(self, size, rng):
28 noise = rng.standard_normal((size, len(self.mean)))
29 return self.mean + noise @ self.transform.T, noise
30
31 def adapt(self, noise, gains):
32 order = np.argsort(-gains, kind="stable")
33 ranked = gains[order]
34 if ranked[0] == ranked[-1]:
35 return
36 count = len(gains)
37 utilities = np.maximum(0., np.log(count / 2 + 1) - np.log(np.arange(1, count + 1)))
38 utilities = utilities / utilities.sum() - 1 / count
39 edges = np.r_[0, np.flatnonzero(ranked[1:] != ranked[:-1]) + 1, count]
40 for start, stop in zip(edges[:-1], edges[1:]):
41 utilities[start:stop] = utilities[start:stop].mean()
42 steps = noise[order]
43 self.mean += self.transform @ (utilities @ steps)
44 covariance_gradient = (steps.T * utilities) @ steps
45 eigenvalues, eigenvectors = np.linalg.eigh(covariance_gradient)
46 update = (eigenvectors * np.exp(self.rate / 2 * eigenvalues)) @ eigenvectors.T
47 self.transform = self.transform @ update
48
49
50
51@dataclass(frozen=True)
53 """Add completed generations, learner updates, and xNES restarts to TrainingStats."""
54
55 generations: int = 0
56 gradient_updates: int = 0
57 walk_updates: int = 0
58 restarts: int = 0
59
60
61
63 """Continuous-action PPGA following Batra et al. (ICLR 2024).
64
65 Each descriptor is the episode mean of a caller-supplied timestep
66 measure. Independent PPO learners estimate normalized directions from
67 the same starting actor. The emitter evaluates the center and xNES
68 branches with fresh episodes, updates annealed thresholds, and walks
69 the center using another PPO learner with a weighted reward.
70
71 :param env_factory: Factory for a single Gymnasium environment with a
72 numeric Box observation space and bounded floating-point Box action space.
73 :param archive: Empty scalar, best-only Grid or CVTGrid for measured policies.
74 :param measure: Callable of (observation, action, successor, info) in
75 environment coordinates, returning one value per archive dimension.
76 :param ppo: Optional PPOConfig shared by the gradient and walking stages.
77 :param gradient_updates: PPO collections per objective or measure direction.
78 :param walk_updates: PPO collections per search-policy walk.
79 :param population_size: Number of xNES branches per iteration.
80 :param sigma0: Initial xNES standard deviation in coefficient space.
81 :param threshold_min: Initial cell threshold in episodic return units.
82 :param learning_rate: Annealing rate for threshold updates, in (0, 1].
83 :param policy: Optional PolicyConfig for the continuous actor.
84 :param evaluation_episodes: Complete episodes per candidate score.
85 :param max_episode_steps: Truncation horizon for training and evaluation.
86 :param seed: Seed for policies, coefficients, and environment resets.
87 :param device: PyTorch device.
88 :param on_step: Callback of (archive, stats) after each measured policy.
89 """
90
91 _stochastic_box = True
92 _whole_episodes = False
93 _stats_class = PPGAStats
94
95 def __init__(self, env_factory, archive, *, measure, ppo=None, gradient_updates=1, walk_updates=1,
96 population_size=16, sigma0=.1, threshold_min=0., learning_rate=.1, policy=None,
97 evaluation_episodes=1, max_episode_steps=300, seed=0, device="cpu", on_step=None):
98 if not callable(measure):
99 raise TypeError("measure must be callable.")
100 self.ppo = PPOConfig() if ppo is None else ppo
101 if not isinstance(self.ppo, PPOConfig):
102 raise TypeError("ppo must be a PPOConfig.")
103 if not (0 < sigma0 < np.inf and np.isfinite(threshold_min) and 0 < learning_rate <= 1):
104 raise ValueError("Provide a finite positive sigma0, finite threshold_min and learning_rate in (0, 1].")
105 self._gradient_updates = _integer(gradient_updates, "gradient_updates")
106 self._walk_updates = _integer(walk_updates, "walk_updates")
107 self._population = _integer(population_size, "population_size", 2)
108 self._measure = measure
109 self._sigma0, self._threshold_min, self._learning_rate = sigma0, threshold_min, learning_rate
110 super().__init__(env_factory, archive, descriptor=self._unavailable_descriptor, policy=policy,
111 evaluation_episodes=evaluation_episodes, max_episode_steps=max_episode_steps,
112 seed=seed, device=device, on_step=on_step)
113 if self._whole_episodes and self.ppo.rollout_steps < self._horizon:
114 raise ValueError("PPO rollout_steps must cover at least one full episode.")
115 self._measures = len(self.archive.features_domain)
116 self._center = self._actor._parameters()
117 self._thresholds = {}
118 self._nes = _XNES(self._measures + 1, sigma0)
119
120 @staticmethod
121 def _unavailable_descriptor(episode):
122 raise RuntimeError("PPGA descriptors require recorded timestep measures.")
123
124 def _build_actor(self, env, config, seed, device):
125 actor = super()._build_actor(env, config, seed, device)
126 if not isinstance(actor._actions, _BoxLayout):
127 raise ValueError("PPGA requires a bounded floating-point Box action space.")
128 return actor
129
130 @property
131 def stats(self):
132 """Return cumulative policy and interaction statistics."""
133 return self._stats_class(**self._counts)
134
135 @property
137 """Return the worst-case number of environment steps in one generation."""
138 updates = (self._measures + 1) * self._gradient_updates + self._walk_updates
139 return updates * self.ppo.rollout_steps + (self._population + 1) * self._episodes * self._horizon
140
141 def _components(self, observations, actions, successors, infos):
142 shape = self._actor._obs_shape
143 values = np.asarray([self._measure(obs.reshape(shape), action, nxt.reshape(shape), info)
144 for obs, action, nxt, info in zip(observations, actions, successors, infos)],
145 dtype=float)
146 if values.shape != (len(observations), self._measures) or not np.isfinite(values).all():
147 raise ValueError(f"measure must return {self._measures} finite values per step.")
148 return values
149
150 def _objective(self, observations, actions, rewards):
151 return np.asarray(rewards, dtype=float)
152
153 def _trajectory_objective(self, observations, actions, rewards, measures):
154 return self._objective(observations, actions, rewards)
155
156 def _bonus(self, measures, ended):
157 return 0.
158
159 def _after_generation(self):
160 pass
161
162 def _coefficient_weights(self, weights):
163 return weights
164
165 def _reward(self, weights, *, stage=None):
166 def transform(observations, actions, successors, rewards, ended, infos):
167 measures = self._components(observations, actions, successors, infos)
168 result = measures @ weights[1:]
169 if weights[0]:
170 objective = self._objective(observations, actions, rewards)
171 result += weights[0] * (objective + self._bonus(measures, ended))
172 return result
173 return transform
174
175 def _ppo_move(self, cursor, budget, weights, updates, counter):
176 learner = _Learner(self._actor, self.ppo, _seed(self._training_rng))
177 transform = self._reward(weights, stage=counter)
178 # End collection for the preceding learner. Its successor can still be
179 # used as a bootstrap target, but each new direction starts with a reset.
180 cursor.ended = True
181 for _ in range(updates):
182 learner.update(cursor, budget, self.ppo.rollout_steps, reward_transform=transform,
183 whole_episodes=self._whole_episodes)
184 self._counts[counter] += 1
185
186 def _score_candidate(self, cursor, budget, vector):
187 self._actor._set_parameters(vector)
188 self._counts["candidate_attempts"] += 1
189 episodes, descriptors, objectives = [], [], []
190 for _ in range(self._episodes):
191 steps = []
192
193 def record(obs, action, reward, successor, terminated, truncated, info):
194 steps.append((obs, action, successor, deepcopy(info)))
195
196 episode = _evaluate_episode(cursor, self._actor, budget, transition_info=record)
197 obs, actions, successors, infos = zip(*steps)
198 measures = self._components(obs, actions, successors, infos)
199 descriptors.append(measures.mean(axis=0))
200 objectives.append(self._trajectory_objective(obs, actions, episode.rewards, measures).sum())
201 episodes.append(episode)
202 self._counts["evaluated_policies"] += 1
203 quality = float(np.mean(objectives))
204 features = tuple(np.mean(descriptors, axis=0))
205 self._offer(episodes, "ppga", descriptors=descriptors, quality=quality)
206
207 gain = -np.inf
208 if (self.archive.in_bounds(features, self.archive.features_domain)
209 and self.archive.in_bounds((quality,), self.archive.fitness_domain)):
210 cell = self.archive.index_grid(features)
211 threshold = self._thresholds.get(cell, self._threshold_min)
212 gain = quality - threshold
213 if gain > 0:
214 self._thresholds[cell] = (1 - self._learning_rate) * threshold + self._learning_rate * quality
215 if self._on_step is not None:
216 self._on_step(self.archive, self.stats)
217 return gain
218
219 def _generation(self, cursor, evaluation, budget):
220 basis = []
221 for weights in np.eye(self._measures + 1):
222 self._actor._set_parameters(self._center)
223 self._ppo_move(cursor, budget, weights, self._gradient_updates, "gradient_updates")
224 basis.append(self._actor._parameters().astype(float) - self._center)
225 basis = _gradient_basis(np.asarray(basis), 1.)
226 center_gain = self._score_candidate(evaluation, budget, self._center)
227 coeffs, noise = self._nes.sample(self._population, self._selection_rng)
228 offsets = self._coefficient_weights(coeffs) @ basis
229 gains = np.asarray([self._score_candidate(evaluation, budget, self._center + offset)
230 for offset in offsets])
231 self._nes.adapt(noise, gains)
232 self._actor._set_parameters(self._center)
233 self._ppo_move(cursor, budget, self._coefficient_weights(self._nes.mean),
234 self._walk_updates, "walk_updates")
235 self._center = self._actor._parameters()
236 if center_gain <= 0 and np.all(gains <= 0):
237 self._nes = _XNES(self._measures + 1, self._sigma0)
238 if self.archive:
239 self._center = np.asarray(self._parent(), dtype=np.float32)
240 self._counts["restarts"] += 1
241 self._after_generation()
242 self._counts["generations"] += 1
243
244
245 def train(self, max_env_steps):
246 """Return cumulative stats. Unspent steps from a call are not carried forward."""
247 budget = _StepBudget(max_env_steps, self._counts)
248 if budget.remaining >= self.generation_step_limit:
249 with _open_environment(self._factory) as env:
250 _check_spaces(env, self._actor)
251 training = _Cursor(env, self._actor, self._horizon, self._training_rng)
252 evaluation = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
253 while budget.remaining >= self.generation_step_limit:
254 self._generation(training, evaluation, budget)
255 return self.stats
Report PPGA generations and step expenditures alongside native search statistics.
Definition ppga.py:52
Branch from PPO objective and descriptor directions and walk with xNES.
Definition ppga.py:62
_unavailable_descriptor(episode)
Definition ppga.py:121
dict _thresholds
Definition ppga.py:117
_objective(self, observations, actions, rewards)
Definition ppga.py:150
train(self, max_env_steps)
Run complete PPGA generations within an additional environment step limit.
Definition ppga.py:245
bool _whole_episodes
Definition ppga.py:92
generation_step_limit(self)
Definition ppga.py:136
_generation(self, cursor, evaluation, budget)
Definition ppga.py:219
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
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