48 """Store one achieved fragment and one selected target per team transition."""
50 def __init__(self, capacity, actor, domain, feature, radius):
51 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
53 self.
fragments = np.empty((capacity, len(domain.bounds)), dtype=np.float32)
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
69 self.
actions[slots], self.
rewards[slots] = actions[start:], rewards[start:]
71 self.
terminated[slots[-1]] = episode.terminated
76 relabel = rng.random(keep) < relabel_probability
77 self.
goals[slots] = np.where(relabel[:,
None], self.
fragments[slots], target)
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))
87 def __init__(self, search, actor, config, seed):
89 self.
rng = np.random.default_rng(seed)
90 dimension = len(search._domain.bounds)
92 search._fragment_feature, search._radius)
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)
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)
106 def record(self, episode, achieved, target, relabel_probability):
107 self.
replay.record(episode, target, relabel_probability, self.
rng)
109 def _step(self, loss, optimizer, name):
110 if not torch.isfinite(loss):
111 raise ValueError(f
"MIQD produced a nonfinite {name} loss.")
113 _checked_step(optimizer)
115 self.
counts[
"optimizer_steps"] += 1
117 def _information_reward(self, states, actions, achieved, goal):
118 if not self.
search._information_weight:
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))
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)
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]
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)
155 states, actions, rewards, successor, terminal, fragments, goals = self.
replay.sample(
158 with torch.no_grad():
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)
166 def refine(self, parameters, target, steps):
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()
187 """Learn distinct cooperative behaviors with a centralized joint critic.
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.
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.
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.")
213 self.
_radius = _integer(fragment_radius,
"fragment_radius", 0)
216 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
218 def _make_team_learner(self, config, length_scale):
220 raise ValueError(
"MIQD needs at least two rows per information minibatch.")
223 def _refine_team(self, parameters):
225 target = self.
_domain.normalize(self.
_parent().features.values, goal=
True)
228 def _fit_team_distribution(self, policies):
235 """Return the team search and auxiliary learning counts."""