63 """Continuous-action PPGA following Batra et al. (ICLR 2024).
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.
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.
91 _stochastic_box =
True
92 _whole_episodes =
False
93 _stats_class = PPGAStats
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.")
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].")
107 self.
_population = _integer(population_size,
"population_size", 2)
111 evaluation_episodes=evaluation_episodes, max_episode_steps=max_episode_steps,
112 seed=seed, device=device, on_step=on_step)
114 raise ValueError(
"PPO rollout_steps must cover at least one full episode.")
121 def _unavailable_descriptor(episode):
122 raise RuntimeError(
"PPGA descriptors require recorded timestep measures.")
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.")
132 """Return cumulative policy and interaction statistics."""
137 """Return the worst-case number of environment steps in one generation."""
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)],
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.")
150 def _objective(self, observations, actions, rewards):
151 return np.asarray(rewards, dtype=float)
153 def _trajectory_objective(self, observations, actions, rewards, measures):
154 return self.
_objective(observations, actions, rewards)
156 def _bonus(self, measures, ended):
159 def _after_generation(self):
162 def _coefficient_weights(self, weights):
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:]
170 objective = self._objective(observations, actions, rewards)
171 result += weights[0] * (objective + self._bonus(measures, ended))
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)
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
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):
193 def record(obs, action, reward, successor, terminated, truncated, info):
194 steps.append((obs, action, successor, deepcopy(info)))
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)
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
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)
219 def _generation(self, cursor, evaluation, budget):
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)
239 self._center = np.asarray(self._parent(), dtype=np.float32)
240 self._counts[
"restarts"] += 1
241 self._after_generation()
242 self._counts[
"generations"] += 1
246 """Return cumulative stats. Unspent steps from a call are not carried forward."""
249 with _open_environment(self.
_factory)
as env:
250 _check_spaces(env, self.
_actor)