7"""Estimate discounted occupancy ratios and use them in Stein policy gradients."""
9from collections
import Counter
10from dataclasses
import dataclass
11from math
import isfinite, log, prod
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
21__all__ = [
"QDDualDICEJS",
"QDDualDICEConfig",
"QDDualDICEStats"]
25@dataclass(frozen=True)
27 """Set discount, kernel temperature, sample counts, and learning rates.
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.
36 temperature: float = .2
37 diversity_weight: float = 1.
38 episodes_per_update: int = 4
40 dice_hidden_sizes: tuple[int, ...] = (32, 32)
41 dice_learning_rate: float = .003
42 actor_learning_rate: float = .003
44 def __post_init__(self):
48 raise ValueError(
"Use a discount in [0, 1), finite positive rates and temperature, and nonnegative repulsion.")
55@dataclass(frozen=True)
57 """Count optimizer steps one per actor or per network in a directed pair."""
59 training_steps: int = 0
61 cutoff_episodes: int = 0
62 ensemble_updates: int = 0
63 estimator_steps: int = 0
68 """Return the number of real environment transitions."""
72@dataclass(frozen=True)
74 observations: torch.Tensor
79@dataclass(frozen=True)
83 successor_observations: torch.Tensor
84 regular_successor: torch.Tensor
85 initial_observations: torch.Tensor
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()
95def _points(actor, observations, controls):
96 return torch.cat((observations, _action_features(actor, controls),
97 observations.new_zeros((len(observations), 1))), dim=1)
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)
107 controls = actor._sample(outputs, actor._log_std.clamp(-12., 2.), actor._rng)
108 return _points(actor, observations, controls)
111def _absorption(points):
112 result = points.new_zeros(points.shape[-1])
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])
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)
131def _expected(values, weights):
132 return torch.dot(values.reshape(-1), weights)
136 """Use the Fenchel saddle objective to estimate source/behavior density ratios."""
138 def __init__(self, width, config, seeds, device):
140 self.
potential, self.
dual = (_mlp(width, 1, architecture, _seed(seeds), device)
for _
in range(2))
142 torch.nn.init.zeros_(network[-1].weight)
143 torch.nn.init.zeros_(network[-1].bias)
145 self.
dual_optimizer = torch.optim.Adam(self.
dual.parameters(), lr=config.dice_learning_rate)
146 self.
gamma = config.gamma
148 def _difference(self, points, next_points):
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():
156 ratio = 1. + self.
dual(points).squeeze(-1)
158 (0.5 * _expected((ratio - target).square(), weights)).backward()
160 with torch.no_grad():
161 ratio = 1. + self.
dual(points).squeeze(-1)
164 loss = _expected(difference * ratio, weights) - (1. - self.
gamma) * self.
potential(initial_points).mean()
170 """Score the nonnegative estimated ratio at the supplied occupancy rows."""
171 return (1. + self.
dual(points).squeeze(-1)).clamp_min(0.).log1p()
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,
181def _discounted_credit(rewards, gamma, tail=0.):
182 """Credit each action with its contribution to normalized discounted return."""
184 values = rewards.detach().double().cpu().numpy()
185 result = np.empty_like(values)
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)
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.))
200 """Apply reward and Jensen-Shannon Stein gradients to a policy ensemble.
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.
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.
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.")
223 self.
_size = _integer(population_size,
"population_size", 2)
224 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
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))
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
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)
247 """Return cumulative interactions and optimizer work."""
252 """Return the latest symmetric Jensen-Shannon estimates before the actor update."""
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())
264 def _collect(self, cursor, actor, budget):
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])
273 return _DICETrajectory(actor._tensor(np.stack(observations)), torch.stack(controls),
274 actor._tensor(rewards))
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
287 def _actor_gradients(self, source, divergences, logs):
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]))
294 task = torch.cat([_discounted_credit(row.rewards, gamma)
for row
in rows])
296 for target
in range(self.
_size):
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))
309 panels = tuple(_panel(actor, rows, self.
config.gamma)
for actor, rows
in zip(self.
_actors, self.
_episodes))
311 for (i, j), pair
in self.
_pairs.items():
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):
317 divergences[i, j] = divergences[j, i] = _js_divergence(logs[j, i], panels[i].weights,
318 logs[i, j], panels[j].weights)
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)
325 self.
_counts[
"actor_steps"] += 1
326 self.
_divergences = tuple(map(tuple, divergences.cpu().tolist()))
327 self.
_counts[
"ensemble_updates"] += 1
335 """Train on completed episodes and keep unfinished panels across calls.
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.
342 with _open_environment(self.
_factory)
as env:
343 _check_spaces(env, self.
_actors[0])
345 while budget.remaining:
347 episode = self.
_collect(cursor, actor, budget)
349 self.
_counts[
"cutoff_episodes"] += 1
Architecture of the actor and, for PPO, the separate value network.
Configure the two-timescale occupancy estimator and policy ensemble.
float actor_learning_rate
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.
log_one_plus_ratio(self, points)
update(self, points, next_points, initial_points, weights)
_difference(self, points, next_points)