QDpy
Loading...
Searching...
No Matches
qd_dualdice.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Estimate discounted occupancy ratios and use them in Stein policy gradients."""
8
9from collections import Counter
10from dataclasses import dataclass
11from math import isfinite, log, prod
12
13import numpy as np
14import torch
15from torch.nn import functional as F
16
17from .policy import (CategoricalPolicy, PolicyConfig, _distributions, _integer, _joint_statistics,
18 _make_policy, _mlp, _squashed_log_prob)
19from .rollout import _Cursor, _StepBudget, _check_spaces, _open_environment, _seed
20
21__all__ = ["QDDualDICEJS", "QDDualDICEConfig", "QDDualDICEStats"]
22
23
24
25@dataclass(frozen=True)
27 """Set discount, kernel temperature, sample counts, and learning rates.
28
29 Each update collects ``episodes_per_update`` completed rollouts per
30 member. ``dice_steps`` pairs of dual and primal updates are performed
31 for every directed pair. Use ``diversity_weight=0`` to switch off the
32 repulsive term while keeping kernel-weighted reward gradients.
33 """
34
35 gamma: float = .95
36 temperature: float = .2
37 diversity_weight: float = 1.
38 episodes_per_update: int = 4
39 dice_steps: int = 8
40 dice_hidden_sizes: tuple[int, ...] = (32, 32)
41 dice_learning_rate: float = .003
42 actor_learning_rate: float = .003
43
44 def __post_init__(self):
45 if not (0 <= self.gamma < 1. and 0 < self.temperature < np.inf
46 and 0 <= self.diversity_weight < np.inf
47 and 0 < self.dice_learning_rate < np.inf and 0 < self.actor_learning_rate < np.inf):
48 raise ValueError("Use a discount in [0, 1), finite positive rates and temperature, and nonnegative repulsion.")
49 _integer(self.episodes_per_update, "episodes_per_update")
50 _integer(self.dice_steps, "dice_steps")
51 object.__setattr__(self, "dice_hidden_sizes", PolicyConfig(self.dice_hidden_sizes).hidden_sizes)
52
53
54
55@dataclass(frozen=True)
57 """Count optimizer steps one per actor or per network in a directed pair."""
58
59 training_steps: int = 0
60 episodes: int = 0
61 cutoff_episodes: int = 0
62 ensemble_updates: int = 0
63 estimator_steps: int = 0
64 actor_steps: int = 0
65
66 @property
67 def env_steps(self):
68 """Return the number of real environment transitions."""
69 return self.training_steps
70
71
72@dataclass(frozen=True)
74 observations: torch.Tensor
75 actions: torch.Tensor
76 rewards: torch.Tensor
77
78
79@dataclass(frozen=True)
81 points: torch.Tensor
82 weights: torch.Tensor
83 successor_observations: torch.Tensor
84 regular_successor: torch.Tensor
85 initial_observations: torch.Tensor
86
87
88def _action_features(actor, controls):
89 if isinstance(actor, CategoricalPolicy):
90 return torch.cat([F.one_hot(controls[:, i], width)
91 for i, width in enumerate(actor._actions.counts)], dim=1).float()
92 return controls.tanh()
93
94
95def _points(actor, observations, controls):
96 return torch.cat((observations, _action_features(actor, controls),
97 observations.new_zeros((len(observations), 1))), dim=1)
98
99
100@torch.no_grad()
101def _policy_points(actor, observations):
102 outputs = actor._network(observations)
103 if isinstance(actor, CategoricalPolicy):
104 controls = torch.cat([torch.multinomial(factor.probs, 1, generator=actor._rng)
105 for factor in _distributions(outputs, actor._actions.counts)], dim=1)
106 else:
107 controls = actor._sample(outputs, actor._log_std.clamp(-12., 2.), actor._rng)
108 return _points(actor, observations, controls)
109
110
111def _absorption(points):
112 result = points.new_zeros(points.shape[-1])
113 result[-1] = 1.
114 return result
115
116
117def _panel(actor, trajectories, gamma):
118 counts = [len(row.rewards) for row in trajectories]
119 real = [_points(actor, row.observations, row.actions) for row in trajectories]
120 absorber = _absorption(real[0])[None]
121 points = torch.cat([torch.cat((batch, absorber)) for batch in real])
122 # Every complete episode contributes probability one, including its infinite absorbing tail.
123 weights = points.new_tensor([weight for length in counts for weight in
124 (*((1. - gamma) * gamma ** np.arange(length)), gamma ** length)])
125 successor = torch.cat([row.observations[1:] for row in trajectories])
126 mask = torch.cat([torch.arange(n + 1, device=points.device) < n - 1 for n in counts])
127 initial = torch.stack([row.observations[0] for row in trajectories])
128 return _OccupancyPanel(points, weights / len(trajectories), successor, mask, initial)
129
130
131def _expected(values, weights):
132 return torch.dot(values.reshape(-1), weights)
133
134
136 """Use the Fenchel saddle objective to estimate source/behavior density ratios."""
137
138 def __init__(self, width, config, seeds, device):
139 architecture = PolicyConfig(config.dice_hidden_sizes)
140 self.potential, self.dual = (_mlp(width, 1, architecture, _seed(seeds), device) for _ in range(2))
141 for network in (self.potential, self.dual):
142 torch.nn.init.zeros_(network[-1].weight)
143 torch.nn.init.zeros_(network[-1].bias)
144 self.potential_optimizer = torch.optim.Adam(self.potential.parameters(), lr=config.dice_learning_rate)
145 self.dual_optimizer = torch.optim.Adam(self.dual.parameters(), lr=config.dice_learning_rate)
146 self.gamma = config.gamma
147
148 def _difference(self, points, next_points):
149 # Center the potential at 1/(1-gamma) and the ratio at one.
150 return 1. + self.potential(points).squeeze(-1) - self.gamma * self.potential(next_points).squeeze(-1)
151
152 def update(self, points, next_points, initial_points, weights):
153 """Ascend the dual, then descend the potential using the updated dual."""
154 with torch.no_grad():
155 target = self._difference(points, next_points)
156 ratio = 1. + self.dual(points).squeeze(-1)
157 self.dual_optimizer.zero_grad()
158 (0.5 * _expected((ratio - target).square(), weights)).backward()
159 self.dual_optimizer.step()
160 with torch.no_grad():
161 ratio = 1. + self.dual(points).squeeze(-1)
162 self.potential_optimizer.zero_grad()
163 difference = self._difference(points, next_points)
164 loss = _expected(difference * ratio, weights) - (1. - self.gamma) * self.potential(initial_points).mean()
165 loss.backward()
166 self.potential_optimizer.step()
167
168 @torch.no_grad()
169 def log_one_plus_ratio(self, points):
170 """Score the nonnegative estimated ratio at the supplied occupancy rows."""
171 return (1. + self.dual(points).squeeze(-1)).clamp_min(0.).log1p()
172
173
174def _log_probabilities(actor, observations, actions):
175 if isinstance(actor, CategoricalPolicy):
176 return _joint_statistics(actor._network(observations), actions, actor._actions.counts)[0]
177 return _squashed_log_prob(actor._network(observations), actor._log_std.clamp(-12., 2.), actions,
178 actor._log_scale)
179
180
181def _discounted_credit(rewards, gamma, tail=0.):
182 """Credit each action with its contribution to normalized discounted return."""
183 # The tail is the common reward obtained at every absorbing step.
184 values = rewards.detach().double().cpu().numpy()
185 result = np.empty_like(values)
186 running = tail
187 for i in range(len(values) - 1, -1, -1):
188 running = (1. - gamma) * values[i] + gamma * running
189 result[i] = gamma ** i * running
190 return rewards.new_tensor(result)
191
192
193def _js_divergence(source_logs, source_weights, target_logs, target_weights):
194 value = log(2.) - .5 * (_expected(source_logs, source_weights) + _expected(target_logs, target_weights))
195 return value.clamp(0., log(2.))
196
197
198
200 """Apply reward and Jensen-Shannon Stein gradients to a policy ensemble.
201
202 A pair of neural networks estimates each directed occupancy ratio.
203 Evaluate the kernel and detached divergence pseudo-rewards on
204 current-policy trajectories. Use normalized, discounted score-function
205 policy gradients and apply every member's Stein update simultaneously.
206 A common implicit absorbing state represents completed episodes without
207 additional simulator calls.
208
209 :param env_factory: Callable creating one Gymnasium Box-observation environment.
210 :param population_size: Number of stochastic policies, at least two.
211 :param policy: Optional native PolicyConfig for the actors.
212 :param config: Optional QDDualDICEConfig for the estimator and kernel.
213 :param max_episode_steps: Finite rollout limit, treated as an episodic boundary.
214 :param seed: Private seed for actors, estimator, and environment resets.
215 :param device: PyTorch CPU or CUDA device.
216 """
217
218 def __init__(self, env_factory, *, population_size=3, policy=None, config=None,
219 max_episode_steps=200, seed=0, device="cpu"):
220 if not callable(env_factory):
221 raise TypeError("env_factory must be callable.")
222 self._factory = env_factory
223 self._size = _integer(population_size, "population_size", 2)
224 self._horizon = _integer(max_episode_steps, "max_episode_steps")
225 self.config = QDDualDICEConfig() if config is None else config
226 if not isinstance(self.config, QDDualDICEConfig):
227 raise TypeError("config must be a QDDualDICEConfig.")
228 actor_seeds, dice_seeds, self._seeds = map(
229 np.random.default_rng, np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(3))
230 with _open_environment(env_factory) as env:
231 self._actors = tuple(_make_policy(env, policy, _seed(actor_seeds), device, stochastic=True)
232 for _ in range(self._size))
233 first = self._actors[0]
234 action_width = sum(first._actions.counts) if isinstance(first, CategoricalPolicy) else prod(first._actions.shape)
235 width = prod(first._obs_shape) + action_width + 1
236 self._pairs = {(i, j): _DualDICEPair(width, self.config, dice_seeds, first.device)
237 for i in range(self._size) for j in range(self._size) if i != j}
238 self._optimizers = [torch.optim.Adam(actor._trainable_parameters(), lr=self.config.actor_learning_rate)
239 for actor in self._actors]
240 self._episodes = [[] for _ in self._actors]
241 self._member = 0
242 self._counts = Counter()
243 self._divergences = None
244
245 @property
246 def stats(self):
247 """Return cumulative interactions and optimizer work."""
248 return QDDualDICEStats(**self._counts)
249
250 @property
252 """Return the latest symmetric Jensen-Shannon estimates before the actor update."""
253 return self._divergences
254
255
256 def policies(self, *, device=None, seed=0):
257 """Return independent portable actors in stable ensemble order."""
258 seed = _integer(seed, "seed", 0)
259 copies = tuple(actor._new(seed + i, device) for i, actor in enumerate(self._actors))
260 for current, copy in zip(self._actors, copies):
261 copy._set_parameters(current._parameters())
262 return copies
263
264 def _collect(self, cursor, actor, budget):
265 cursor.reset()
266 observations, controls, rewards = [], [], []
267 while budget.remaining:
268 observations.append(cursor.observation)
269 action, control, _ = actor._draw(cursor.observation, False, actor._rng)
270 controls.append(control)
271 rewards.append(cursor.step(action, budget, "training_steps")[0])
272 if cursor.ended:
273 return _DICETrajectory(actor._tensor(np.stack(observations)), torch.stack(controls),
274 actor._tensor(rewards))
275 return None
276
277 def _fit_pair(self, pair, target, panel):
278 for _ in range(self.config.dice_steps):
279 with torch.no_grad():
280 next_points = _absorption(panel.points).expand_as(panel.points).clone()
281 if len(panel.successor_observations):
282 next_points[panel.regular_successor] = _policy_points(target, panel.successor_observations)
283 initial = _policy_points(target, panel.initial_observations)
284 pair.update(panel.points, next_points, initial, panel.weights)
285 self._counts["estimator_steps"] += 2
286
287 def _actor_gradients(self, source, divergences, logs):
288 actor, rows = self._actors[source], self._episodes[source]
289 sizes = [len(row.rewards) + 1 for row in rows]
290 parameters = actor._trainable_parameters()
291 log_p = _log_probabilities(actor, torch.cat([row.observations for row in rows]),
292 torch.cat([row.actions for row in rows]))
293 gamma = self.config.gamma
294 task = torch.cat([_discounted_credit(row.rewards, gamma) for row in rows])
295 gradients = []
296 for target in range(self._size):
297 advantage = task
298 if target != source and self.config.diversity_weight:
299 pseudo = -.5 * logs[target, source]
300 novelty = torch.cat([_discounted_credit(values[:-1], gamma, float(values[-1]))
301 for values in pseudo.split(sizes)])
302 advantage = task - (self.config.diversity_weight / self.config.temperature) * novelty
303 affinity = torch.exp(-divergences[target, source] / self.config.temperature)
304 objective = affinity * torch.dot(advantage, log_p) / (self._size * len(rows))
305 gradients.append(torch.autograd.grad(-objective, parameters, retain_graph=target + 1 < self._size))
306 return gradients
307
308 def _update(self):
309 panels = tuple(_panel(actor, rows, self.config.gamma) for actor, rows in zip(self._actors, self._episodes))
310 logs = {}
311 for (i, j), pair in self._pairs.items():
312 self._fit_pair(pair, self._actors[i], panels[j])
313 logs[i, j] = pair.log_one_plus_ratio(panels[j].points)
314 divergences = panels[0].points.new_zeros((self._size, self._size))
315 for i in range(self._size):
316 for j in range(i):
317 divergences[i, j] = divergences[j, i] = _js_divergence(logs[j, i], panels[i].weights,
318 logs[i, j], panels[j].weights)
319 contributions = [self._actor_gradients(source, divergences, logs) for source in range(self._size)]
320 for i, (actor, optimizer) in enumerate(zip(self._actors, self._optimizers)):
321 optimizer.zero_grad()
322 for parameter, column in zip(actor._trainable_parameters(), zip(*(row[i] for row in contributions))):
323 parameter.grad = torch.stack(column).sum(dim=0)
324 optimizer.step()
325 self._counts["actor_steps"] += 1
326 self._divergences = tuple(map(tuple, divergences.cpu().tolist()))
327 self._counts["ensemble_updates"] += 1
328 self._episodes = [[] for _ in self._actors]
329
330
333 @torch.enable_grad()
334 def train(self, max_env_steps):
335 """Train on completed episodes and keep unfinished panels across calls.
336
337 An episode cut by the step budget is counted and discarded.
338 Completed episodes remain in their panel until every actor has
339 supplied its configured number of episodes.
340 """
341 budget = _StepBudget(max_env_steps, self._counts)
342 with _open_environment(self._factory) as env:
343 _check_spaces(env, self._actors[0])
344 cursor = _Cursor(env, self._actors[0], self._horizon, self._seeds)
345 while budget.remaining:
346 actor = self._actors[self._member]
347 episode = self._collect(cursor, actor, budget)
348 if episode is None:
349 self._counts["cutoff_episodes"] += 1
350 break
351 self._episodes[self._member].append(episode)
352 self._counts["episodes"] += 1
353 self._member = (self._member + 1) % self._size
354 if self._member == 0 and len(self._episodes[0]) == self.config.episodes_per_update:
355 self._update()
356 return self.stats
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Configure the two-timescale occupancy estimator and policy ensemble.
Train exportable Gymnasium policies using the QD-DualDICE-JS population update.
train(self, max_env_steps)
Spend another hard interaction budget on the current ensemble.
policies(self, *, device=None, seed=0)
Export independent copies of the current actors.
_collect(self, cursor, actor, budget)
_actor_gradients(self, source, divergences, logs)
_fit_pair(self, pair, target, panel)
Count simulator work independently of density estimation and actor updates.
update(self, points, next_points, initial_points, weights)
_difference(self, points, next_points)