QDpy
Loading...
Searching...
No Matches
miqd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Fragment-conditioned centralized policy gradients and team CEM."""
7
8from copy import deepcopy
9from dataclasses import dataclass
10from math import log, prod
11
12import numpy as np
13from scipy.spatial.distance import cdist
14import torch
15from torch.nn import functional as F
16
17from .masqd import MASQD, MASQDStats
18from .policy import PolicyConfig, _integer, _mlp
19from .rollout import _seed
20from .td3 import _Replay, _checked_step, _critic, _polyak
21
22__all__ = ["MIQD", "MIQDStats"]
23
24
25
26@dataclass(frozen=True)
28 """Count critic, information-estimator, and archived-policy target computation."""
29
30 information_updates: int = 0
31 target_policy_queries: int = 0
32
33
34def _fragment_means(features, radius):
35 """Apply the paper's two centered means, shortening windows at episode edges."""
36 rows = np.arange(len(features))
37 left = np.maximum(rows - radius, 0)
38 right = np.minimum(rows + radius + 1, len(features))
39
40 def average(matrix):
41 prefix = np.vstack((np.zeros((1, matrix.shape[1])), np.cumsum(matrix, axis=0, dtype=float)))
42 return (prefix[right] - prefix[left]) / (right - left)[:, None]
43
44 return average(average(features)).astype(np.float32)
45
46
48 """Store one achieved fragment and one selected target per team transition."""
49
50 def __init__(self, capacity, actor, domain, feature, radius):
51 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
52 self.actor, self.domain, self.feature, self.radius = actor, domain, feature, radius
53 self.fragments = np.empty((capacity, len(domain.bounds)), dtype=np.float32)
54 self.goals = np.empty_like(self.fragments)
55
56 def record(self, episode, target, relabel_probability, rng):
57 features = np.stack([self.domain.normalize(self.feature(obs), goal=True)
58 for obs in episode.observations[:-1]])
59 fragments = _fragment_means(features, min(self.radius, episode.steps))
60 observations = episode.observations.reshape(episode.steps + 1, -1)
61 actions = self.actor._encode_actions(np.asarray(episode.actions).reshape(episode.steps, -1))
62 rewards = np.asarray(episode.rewards, dtype=float)
63 if np.any(np.abs(rewards) > np.finfo(np.float32).max):
64 raise ValueError("MIQD replay requires rewards representable in float32.")
65 keep = min(episode.steps, self.capacity)
66 start = episode.steps - keep
67 slots = (self.position + np.arange(start, episode.steps)) % self.capacity
68 self.observations[slots], self.next_observations[slots] = observations[start:-1], observations[start + 1:]
69 self.actions[slots], self.rewards[slots] = actions[start:], rewards[start:]
70 self.terminated[slots] = False
71 self.terminated[slots[-1]] = episode.terminated
72 self.fragments[slots] = fragments[start:]
73 if target is None:
74 self.goals[slots] = self.fragments[slots]
75 else:
76 relabel = rng.random(keep) < relabel_probability
77 self.goals[slots] = np.where(relabel[:, None], self.fragments[slots], target)
78 self.position = (self.position + episode.steps) % self.capacity
79 self.size = min(self.size + episode.steps, self.capacity)
80
81 def batch(self, rows, device):
82 return (*super().batch(rows, device), torch.as_tensor(self.fragments[rows], device=device),
83 torch.as_tensor(self.goals[rows], device=device))
84
85
87 def __init__(self, search, actor, config, seed):
88 self.search, self.actor, self.config, self.counts = search, actor, config, search._counts
89 self.rng = np.random.default_rng(seed)
90 dimension = len(search._domain.bounds)
91 self.replay = _FragmentReplay(config.replay_capacity, actor, search._domain,
92 search._fragment_feature, search._radius)
93 architecture = PolicyConfig(config.critic_hidden_sizes)
94 observation_width, action_width = prod(actor._obs_shape), prod(actor._actions.shape)
95 self.critics = torch.nn.ModuleList(
96 _mlp(observation_width + dimension + action_width, 1, architecture, _seed(self.rng),
97 actor.device, torch.nn.ReLU) for _ in range(2)
98 )
99 self.targets = deepcopy(self.critics).requires_grad_(False)
100 self.optimizer = torch.optim.Adam(self.critics.parameters(), lr=config.critic_learning_rate)
101 self.probe = actor._new(_seed(self.rng))
102 self.information = _mlp(observation_width + action_width + dimension, 1, architecture,
103 _seed(self.rng), actor.device, torch.nn.ReLU)
104 self.information_optimizer = torch.optim.Adam(self.information.parameters(), lr=config.critic_learning_rate)
105
106 def record(self, episode, achieved, target, relabel_probability):
107 self.replay.record(episode, target, relabel_probability, self.rng)
108
109 def _step(self, loss, optimizer, name):
110 if not torch.isfinite(loss):
111 raise ValueError(f"MIQD produced a nonfinite {name} loss.")
112 loss.backward()
113 _checked_step(optimizer)
114 self.counts[name] += 1
115 self.counts["optimizer_steps"] += 1
116
117 def _information_reward(self, states, actions, achieved, goal):
118 if not self.search._information_weight:
119 return 0.
120 pairs = torch.cat((states, actions), dim=-1)
121 aligned = self.information(torch.cat((pairs, achieved), dim=-1)).flatten()
122 shifted = achieved.roll(int(self.rng.integers(1, len(achieved))), dims=0)
123 shuffled = self.information(torch.cat((pairs, shifted), dim=-1)).flatten()
124 baseline = shuffled.logsumexp(dim=0) - log(len(shuffled))
125 self.information_optimizer.zero_grad(set_to_none=True)
126 self._step(baseline - aligned.mean(), self.information_optimizer, "information_updates")
127 with torch.no_grad():
128 shuffled = self.information(torch.cat((pairs, shifted), dim=-1)).flatten()
129 baseline = shuffled.logsumexp(dim=0) - log(len(shuffled))
130 score = self.information(torch.cat((pairs, goal), dim=-1)).flatten() - baseline
131 cap = self.search._information_cap
132 return self.search._information_weight * score.clamp(-cap, cap)
133
134 def _population_value(self, successors, goals, terminal):
135 elites = tuple(self.search.archive)
136 result = torch.zeros(len(goals), device=goals.device)
137 live = torch.where(~terminal)[0]
138 if not len(live):
139 return result
140 descriptors = np.stack([self.search._domain.normalize(elite.features.values, goal=True) for elite in elites])
141 distances = cdist(goals[live].cpu().numpy(), descriptors, metric="sqeuclidean")
142 nearest = np.argsort(distances, axis=1, kind="stable")[:, :self.search._target_neighbors]
143 inputs = torch.cat((successors, goals), dim=-1)
144 result[live] = -torch.inf
145 for i in np.unique(nearest):
146 rows = live[torch.as_tensor(np.any(nearest == i, axis=1), device=live.device)]
147 self.probe._set_parameters(elites[i])
148 candidate = self.probe._normalized(successors[rows])
149 first, second = (_critic(critic, inputs[rows], candidate) for critic in self.targets)
150 result[rows] = torch.maximum(result[rows], torch.minimum(first, second))
151 self.counts["target_policy_queries"] += len(rows)
152 return result
153
154 def update(self):
155 states, actions, rewards, successor, terminal, fragments, goals = self.replay.sample(
156 self.config.batch_size, self.rng, self.actor.device)
157 intrinsic = self._information_reward(states, actions, fragments, goals)
158 with torch.no_grad():
159 target = rewards + intrinsic + self.config.gamma * self._population_value(successor, goals, terminal)
160 inputs = torch.cat((states, goals), dim=-1)
161 loss = sum(F.mse_loss(_critic(critic, inputs, actions), target) for critic in self.critics)
162 self.optimizer.zero_grad(set_to_none=True)
163 self._step(loss, self.optimizer, "critic_updates")
164 _polyak(self.critics, self.targets, self.config.tau)
165
166 def refine(self, parameters, target, steps):
167 actor = self.actor
168 actor._set_parameters(parameters)
169 trainable = actor._trainable_parameters()
170 optimizer = torch.optim.Adam(trainable, lr=self.config.actor_learning_rate)
171 for _ in range(steps):
172 states = self.replay.sample_observations(self.config.batch_size, self.rng, actor.device)
173 goals = actor._tensor(target).expand(len(states), -1)
174 loss = -_critic(self.critics[0], torch.cat((states, goals), dim=-1), actor._normalized(states)).mean()
175 if not torch.isfinite(loss):
176 raise ValueError("MIQD produced a nonfinite team policy loss.")
177 for parameter, grad in zip(trainable, torch.autograd.grad(loss, trainable)):
178 parameter.grad = grad
179 _checked_step(optimizer)
180 self.counts["policy_gradient_steps"] += 1
181 self.counts["optimizer_steps"] += 1
182 return actor._parameters()
183
184
185
186class MIQD(MASQD):
187 """Learn distinct cooperative behaviors with a centralized joint critic.
188
189 Use the fixed-agent joint Box adapter, archive, team policy export, and
190 search accounting of MASQD. A separate feature callback supplies bounded
191 state descriptors in the same units as the archive descriptors.
192 Team evaluations always use the external task fitness.
193
194 :param env_factory: Factory for a single joint Gymnasium environment.
195 :param archive: Empty best-only Grid or CVTGrid.
196 :param descriptor: Function of a completed team episode, used by the archive.
197 :param fragment_feature: Function of a joint observation, returning bounded
198 features in archive descriptor coordinates.
199 :param fragment_radius: Half-window size for each centered averaging pass.
200 :param target_neighbors: Maximum number of nearest elites per bootstrap target.
201 :param information_weight: Weight on the MINE density-ratio reward. Zero ablates it.
202 :param information_cap: Bound on the absolute per-transition log-density ratio.
203 :param kwargs: MASQD team, CEM, archive accounting, and optimizer settings.
204 """
205
206 def __init__(self, env_factory, archive, *, descriptor, fragment_feature, fragment_radius=2,
207 target_neighbors=3, information_weight=.1, information_cap=5., **kwargs):
208 if not callable(fragment_feature):
209 raise TypeError("Provide a callable fragment_feature.")
210 if not 0. <= information_weight < np.inf or not 0. < information_cap < np.inf:
211 raise ValueError("Use a finite nonnegative information weight and a finite positive information cap.")
212 self._fragment_feature = fragment_feature
213 self._radius = _integer(fragment_radius, "fragment_radius", 0)
214 self._target_neighbors = _integer(target_neighbors, "target_neighbors")
215 self._information_weight, self._information_cap = information_weight, information_cap
216 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
217
218 def _make_team_learner(self, config, length_scale):
219 if self._information_weight and config.batch_size < 2:
220 raise ValueError("MIQD needs at least two rows per information minibatch.")
221 return _FragmentLearner(self, self._actor._new(_seed(self._training_rng)), config, _seed(self._training_rng))
222
223 def _refine_team(self, parameters):
224 parent = self._parent()
225 target = self._domain.normalize(self._parent().features.values, goal=True)
226 return self._learner.refine(parent, target, self.gradient_steps), target
227
228 def _fit_team_distribution(self, policies):
229 self._mean = self._weights @ policies
230 variance = self._weights @ np.square(policies - self._mean)
231 self._sigma = np.maximum(np.sqrt(variance), self.minimum_sigma)
232
233 @property
234 def stats(self):
235 """Return the team search and auxiliary learning counts."""
236 return MIQDStats(**self._counts, replay_size=self._learner.replay.size)
Cumulative MASQD interactions, critic and variation work, and population updates.
Definition masqd.py:95
Learn diverse teams with diagonal CEM, archive reanchoring, and per-role TD3 critics.
Definition masqd.py:196
Team search statistics with information and population target work.
Definition miqd.py:27
Combine fragment information, neighboring elite targets, and team CEM.
Definition miqd.py:186
_step(self, loss, optimizer, name)
Definition miqd.py:109
_information_reward(self, states, actions, achieved, goal)
Definition miqd.py:117
_population_value(self, successors, goals, terminal)
Definition miqd.py:134
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36