QDpy
Loading...
Searching...
No Matches
qsd_pbt.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Quality-Similar Diversity via population-based reinforcement learning."""
7
8from collections import Counter
9from copy import deepcopy
10from dataclasses import dataclass
11from math import prod
12
13from gymnasium import spaces
14import numpy as np
15import torch
16
17from .policy import CategoricalPolicy, _integer, _mlp
18from .ppo import PPOConfig, _advantages, _surrogate_loss
19from .rollout import Episode, TrainingStats, _Cursor, _StepBudget, _check_spaces, _open_environment, _seed
20
21__all__ = ["QSDPBT", "QSDPBTStats", "QSDPBTEvaluation"]
22
23
24
25@dataclass(frozen=True)
27 """Per-member steps, completed episodes, running returns, and diversity weights."""
28
29 policy_steps: tuple[int, ...] = ()
30 completed_episodes: tuple[int, ...] = ()
31 returns: tuple[float | None, ...] = ()
32 diversity_weights: tuple[float, ...] = ()
33
34
35
36@dataclass(frozen=True)
38 """Mean episode returns, descriptors and audit steps in policy order."""
39
40 returns: tuple[float, ...]
41 descriptors: tuple[tuple[float, ...], ...]
42 steps: int
43
44
45 def diversity_by_quality(self, edges):
46 """Return the mean pairwise descriptor distance for each quality interval.
47
48 Bins include their lower edge, with the final bin also including
49 its upper edge. Empty or one-member intervals return zero.
50 """
51 edges = np.asarray(edges, dtype=float)
52 if edges.ndim != 1 or len(edges) < 2 or not np.isfinite(edges).all() or not np.all(edges[1:] > edges[:-1]):
53 raise ValueError("Use at least two strictly increasing finite quality edges.")
54 returns = np.asarray(self.returns)
55 indices = np.searchsorted(edges, returns, side="right") - 1
56 indices[returns == edges[-1]] -= 1
57 descriptors = np.asarray(self.descriptors)
58 scores = []
59 for index in range(len(edges) - 1):
60 points = descriptors[indices == index]
61 distances = np.linalg.norm(points[:, None] - points[None, :], axis=2)
62 scores.append(float(distances[np.triu_indices(len(points), 1)].mean()) if len(points) > 1 else 0.)
63 return tuple(scores)
64
65
66def _directions(descriptors):
67 """Differentiate mean pairwise Euclidean diversity, choosing zero at ties."""
68 size = len(descriptors)
69 if size < 2:
70 return np.zeros_like(descriptors)
71 difference = descriptors[:, None] - descriptors[None, :]
72 distance = np.linalg.norm(difference, axis=2, keepdims=True)
73 unit = np.divide(difference, distance, out=np.zeros_like(difference), where=distance > 0.)
74 return 2. * unit.sum(axis=1) / (size * (size - 1))
75
76
77class _Agent:
78 """Own one actor, a task critic, and a trajectory descriptor baseline."""
79
80 def __init__(self, actor, config, context_width, descriptor_width, rng):
81 self.actor, self.config = actor, config
82 self.value = _mlp(prod(actor._obs_shape), 1, actor.config, _seed(rng), actor.device)
83 self.behavior = _mlp(context_width, descriptor_width, actor.config, _seed(rng), actor.device)
84 self.parameters = [*actor._trainable_parameters(), *self.value.parameters(), *self.behavior.parameters()]
85 self.optimizer = torch.optim.Adam(self.parameters, lr=config.learning_rate)
86 self.rng = torch.Generator(device=actor.device).manual_seed(_seed(rng))
87 self.reset_rng = np.random.default_rng(_seed(rng))
88 self.quality = self.summary = None
89 self.steps = self.episodes = 0
90 self.weight = 0.
91
92 def learn(self, rows, contexts, descriptors, mask, direction, counts):
93 actor, config = self.actor, self.config
94 states, successors, samples, old_logps, rewards, terminals, truncations = zip(*rows)
95 obs, next_obs = actor._tensor(np.stack(states)), actor._tensor(np.stack(successors))
96 actions, old_logps = torch.stack(samples), torch.stack(old_logps)
97 ctx = actor._tensor(np.asarray(contexts))
98 targets = actor._tensor(descriptors)
99 complete = torch.as_tensor(mask, dtype=torch.bool, device=actor.device)
100 direction = actor._tensor(direction)
101 with torch.no_grad():
102 values = self.value(obs).flatten()
103 task_advantage = _advantages(actor._tensor(rewards), values, self.value(next_obs).flatten(),
104 torch.as_tensor(terminals, device=actor.device),
105 torch.as_tensor(truncations, device=actor.device),
106 config.gamma, config.gae_lambda)
107 returns = task_advantage + values
108 # Direct descriptor advantage replaces the action-dependent expectation
109 # with one completed Monte Carlo target per transition.
110 if len(rows) > 1:
111 task_advantage = (task_advantage - task_advantage.mean()) / (task_advantage.std(unbiased=False) + 1e-8)
112 behavior_advantage = ((targets - self.behavior(ctx)) @ direction).masked_fill(~complete, 0.)
113 advantage = task_advantage + self.weight * behavior_advantage
114
115 for _ in range(config.epochs):
116 order = torch.randperm(len(rows), generator=self.rng, device=actor.device)
117 for batch in order.split(config.batch_size):
118 logps, entropy = actor._ppo_statistics(obs[batch], actions[batch], self.rng)
119 policy_loss = _surrogate_loss(logps, old_logps[batch], advantage[batch], config.clip_ratio)
120 value_loss = .5 * (self.value(obs[batch]).flatten() - returns[batch]).square().mean()
121 valid = batch[complete[batch]]
122 if len(valid):
123 value_loss = value_loss + .5 * (self.behavior(ctx[valid]) - targets[valid]).square().mean()
124 loss = policy_loss + config.value_coef * value_loss - config.entropy_coef * entropy.mean()
125 if not torch.isfinite(loss):
126 raise ValueError("QSD-PBT produced a nonfinite loss.")
127 self.optimizer.zero_grad(set_to_none=True)
128 loss.backward()
129 torch.nn.utils.clip_grad_norm_(self.parameters, config.max_grad_norm, error_if_nonfinite=True)
130 self.optimizer.step()
131 counts["optimizer_steps"] += 1
132
133
134
135class QSDPBT:
136 """Synchronous PPO variant of Quality-Similar Diversity with independent actors.
137
138 :param env_factory: Return a fresh single Gymnasium environment with Discrete or MultiDiscrete actions.
139 :param descriptor: Read a complete Episode and return a fixed finite descriptor vector.
140 :param descriptor_size: Number of descriptor coordinates.
141 :param population_size: Number of independent policies and critics.
142 :param ppo: PPOConfig for task advantages, minibatches, and learning rate.
143 Its rollout length must cover max_episode_steps.
144 :param policy: PolicyConfig for portable actors and the critic networks.
145 :param initial_weight: Starting strength of the diversity advantage.
146 :param decay_steps: Weight decay timescale in per-policy training steps.
147 :param quality_offset: Add this constant to observed episode returns in the
148 adaptive schedule. Choose an offset giving nonnegative adjusted quality.
149 :param ema: Moving average rate for measured episode return and descriptors.
150 :param history: Optional callback (observation, past_actions, past_rewards) returning
151 a finite descriptor-critic context with history_size entries. Omit it
152 to use the flattened state and normalized episode time.
153 :param history_size: Context width when a custom history callback is supplied.
154 :param max_episode_steps: Maximum duration of a complete episode.
155 :param seed: Independent actor, optimizer, and reset streams.
156 :param device: Torch device.
157 """
158
159 def __init__(self, env_factory, *, descriptor, descriptor_size, population_size=4, ppo=None,
160 policy=None, initial_weight=1., decay_steps=10_000, quality_offset=0.,
161 ema=.1, history=None, history_size=None, max_episode_steps=128, seed=0, device="cpu"):
162 if not callable(env_factory) or not callable(descriptor):
163 raise TypeError("Provide an environment factory and an episode descriptor.")
164 if (history is None) != (history_size is None) or (history is not None and not callable(history)):
165 raise ValueError("Provide history and history_size together.")
166 if not (0. <= initial_weight < np.inf and 0. < decay_steps < np.inf
167 and np.isfinite(quality_offset) and 0. < ema <= 1.):
168 raise ValueError("Use finite weights, a positive decay timescale, and ema in (0, 1].")
169 self._factory, self._describe, self._history = env_factory, descriptor, history
170 self._width = _integer(descriptor_size, "descriptor_size")
171 self._horizon = _integer(max_episode_steps, "max_episode_steps")
172 size = _integer(population_size, "population_size", 2)
173 self._config = PPOConfig() if ppo is None else ppo
174 if not isinstance(self._config, PPOConfig) or self._config.rollout_steps < self._horizon:
175 raise ValueError("Use a PPOConfig with rollout_steps at least max_episode_steps.")
176 self._schedule = initial_weight, decay_steps, quality_offset
177 self._ema, self._counts, self._next = ema, Counter(), 0
178 self._agents = []
179 with _open_environment(env_factory) as env:
180 if not isinstance(env.action_space, (spaces.Discrete, spaces.MultiDiscrete)):
181 raise ValueError("QSD-PBT requires a Discrete or MultiDiscrete action space.")
182 for stream in np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(size):
183 rng = np.random.default_rng(stream)
184 actor = CategoricalPolicy(env.observation_space, env.action_space, config=policy,
185 seed=_seed(rng), device=device)
186 self._context_width = (prod(actor._obs_shape) + 1 if history_size is None
187 else _integer(history_size, "history_size"))
188 agent = _Agent(actor, self._config, self._context_width, self._width, rng)
189 agent.weight = initial_weight
190 self._agents.append(agent)
191
192 @property
193 def stats(self):
194 """Return cumulative interactions and the current population estimates."""
195 return QSDPBTStats(**self._counts, policy_steps=tuple(agent.steps for agent in self._agents),
196 completed_episodes=tuple(agent.episodes for agent in self._agents),
197 returns=tuple(agent.quality for agent in self._agents),
198 diversity_weights=tuple(agent.weight for agent in self._agents))
199
200 def _descriptor(self, episode):
201 vector = np.asarray(self._describe(episode), dtype=np.float32)
202 if vector.shape != (self._width,) or not np.isfinite(vector).all():
203 raise ValueError("descriptor must return descriptor_size finite coordinates.")
204 return vector
205
206 def _context(self, observation, actions, rewards):
207 if self._history is None:
208 return np.r_[observation, len(actions) / self._horizon]
209 vector = np.asarray(self._history(observation, tuple(actions), tuple(rewards)), dtype=np.float32)
210 if vector.shape != (self._context_width,) or not np.isfinite(vector).all():
211 raise ValueError("history must return history_size finite coordinates.")
212 return vector.copy()
213
214 def _collect(self, cursor, agent, count, budget, *, audit=False, deterministic=False, rng=None):
215 actor = agent.actor
216 rows, contexts, episodes, ends = [], [], [], []
217 start = 0
218 for _ in range(count):
219 if cursor.ended:
220 if audit and episodes:
221 break
222 initial = deepcopy(cursor.reset())
223 states, actions, rewards = [cursor.observation], [], []
224 observation = cursor.observation.reshape(actor._obs_shape)
225 if audit and deterministic:
226 action = actor._greedy(cursor.observation)
227 else:
228 action, sample, logp = actor._draw(cursor.observation, False, agent.rng if not audit else rng)
229 if not audit:
230 contexts.append(self._context(observation.flatten() if self._history is None else observation,
231 actions, rewards))
232 actions.append(action.copy() if isinstance(action, np.ndarray) else action)
233 phase = "evaluation_steps" if audit else "training_steps"
234 if not audit:
235 agent.steps += 1
236 reward, terminal, truncated, info = cursor.step(action, budget, phase)
237 successors = cursor.observation
238 if not audit:
239 rows.append((states[-1], successors, sample, logp, reward, terminal, truncated))
240 states.append(successors)
241 rewards.append(reward)
242 if cursor.ended:
243 episode = Episode(np.stack(states).reshape(-1, *actor._obs_shape), tuple(actions), tuple(rewards),
244 initial, deepcopy(dict(info)), terminal, truncated)
245 episodes.append(episode)
246 ends.append((start, len(rows)))
247 start = len(rows)
248
249 if audit:
250 return episodes[0]
251 targets = np.zeros((len(rows), self._width), dtype=np.float32)
252 mask = np.zeros(len(rows), dtype=bool)
253 for episode, (start, end) in zip(episodes, ends):
254 vector = self._descriptor(episode)
255 quality = episode.return_
256 if not 0. <= quality + self._schedule[2] < np.inf:
257 raise ValueError("Use a quality_offset giving finite nonnegative adjusted episode returns.")
258 alpha = 1. if agent.episodes == 0 else self._ema
259 agent.quality = quality if agent.quality is None else (1. - alpha) * agent.quality + alpha * quality
260 agent.summary = vector if agent.summary is None else (1. - alpha) * agent.summary + alpha * vector
261 agent.episodes += 1
262 targets[start:end] = vector
263 mask[start:end] = True
264 return rows, contexts, targets, mask
265
266 def _update_population(self):
267 initial, scale, offset = self._schedule
268 known = [index for index, agent in enumerate(self._agents) if agent.episodes]
269 directions = np.zeros((len(self._agents), self._width))
270 if known:
271 points = np.asarray([self._agents[index].summary for index in known], dtype=float)
272 directions[known] = _directions(points)
273 adjusted = [max(0., self._agents[index].quality + offset) for index in known]
274 best = max(adjusted)
275 for index, value in zip(known, adjusted):
276 ratio = best / value if value else (np.inf if best else 1.)
277 agent = self._agents[index]
278 agent.weight = initial * np.exp(-(agent.steps / scale) * ratio)
279 return directions
280
281
282 def train(self, max_env_steps):
283 """Use balanced synchronous blocks. Episode prefixes train only the task critic and actor."""
284 budget = _StepBudget(max_env_steps, self._counts)
285 size = len(self._agents)
286 with _open_environment(self._factory) as env:
287 _check_spaces(env, self._agents[0].actor)
288 while budget.remaining:
289 count = min(budget.remaining, size * self._config.rollout_steps)
290 each, extra = divmod(count, size)
291 batches = []
292 for position in range(size):
293 index = (self._next + position) % size
294 agent = self._agents[index]
295 steps = each + (position < extra)
296 if steps:
297 cursor = _Cursor(env, agent.actor, self._horizon, agent.reset_rng)
298 batches.append((index, self._collect(cursor, agent, steps, budget)))
299 self._next = (self._next + extra) % size
300 directions = self._update_population()
301 for index, batch in batches:
302 self._agents[index].learn(*batch, directions[index], self._counts)
303 return self.stats
304
305
306 def policies(self, *, seed=0, device=None):
307 """Return one portable CategoricalPolicy per population member."""
308 rng = np.random.default_rng(_integer(seed, "seed", 0))
309 actors = []
310 for agent in self._agents:
311 actor = agent.actor._new(_seed(rng), device)
312 actor._set_parameters(agent.actor._parameters())
313 actors.append(actor)
314 return tuple(actors)
315
316
317 def evaluate(self, *, episodes_per_policy=8, seed=1337, deterministic=False):
318 """Evaluate complete episodes with independent reset and action streams."""
319 repetitions = _integer(episodes_per_policy, "episodes_per_policy")
320 seed = _integer(seed, "seed", 0)
321 counts = Counter()
322 budget = _StepBudget(self._horizon * repetitions * len(self._agents), counts)
323 returns, descriptors = [], []
324 with _open_environment(self._factory) as env:
325 _check_spaces(env, self._agents[0].actor)
326 for agent in self._agents:
327 rng = torch.Generator(device=agent.actor.device).manual_seed(seed)
328 cursor = _Cursor(env, agent.actor, self._horizon, np.random.default_rng(seed))
329 episodes = [self._collect(cursor, agent, self._horizon, budget, audit=True,
330 deterministic=deterministic, rng=rng)
331 for _ in range(repetitions)]
332 returns.append(float(np.mean([episode.return_ for episode in episodes])))
333 descriptors.append(tuple(map(float, np.mean([self._descriptor(episode) for episode in episodes],
334 axis=0, dtype=float))))
335 return QSDPBTEvaluation(tuple(returns), tuple(descriptors), counts["evaluation_steps"])
A categorical actor that can run independently of its training environment.
Definition policy.py:222
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
Report individual held-out quality and diversity without updating training.
Definition qsd_pbt.py:37
diversity_by_quality(self, edges)
Compute behavior diversity separately at comparable return levels.
Definition qsd_pbt.py:45
Track exact training work and the observed population at the latest update.
Definition qsd_pbt.py:26
Discover policies with different behaviors at comparable quality levels.
Definition qsd_pbt.py:135
_collect(self, cursor, agent, count, budget, *, audit=False, deterministic=False, rng=None)
Definition qsd_pbt.py:214
evaluate(self, *, episodes_per_policy=8, seed=1337, deterministic=False)
Audit the current population on common held-out reset seeds.
Definition qsd_pbt.py:317
policies(self, *, seed=0, device=None)
Copy numeric actors for independent use and serialization.
Definition qsd_pbt.py:306
_descriptor(self, episode)
Definition qsd_pbt.py:200
train(self, max_env_steps)
Continue training under an additional hard environment-step budget.
Definition qsd_pbt.py:282
_context(self, observation, actions, rewards)
Definition qsd_pbt.py:206
Measurements from a completed evaluation episode.
Definition rollout.py:20
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51