QDpy
Loading...
Searching...
No Matches
masqd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Multiagent Sample-Efficient Quality-Diversity for joint Gymnasium Box tasks."""
7
8from collections import deque
9from copy import deepcopy
10from dataclasses import dataclass
11from math import prod
12
13import numpy as np
14import torch
15from torch import nn
16
17from .descriptor_policy import _DescriptorDomain
18from .descriptor_search import _ConditionedReplay, _Operator, _Proposal, _similarity_rewards
19from .policy import ContinuousPolicy, PolicyConfig, _BoxLayout, _integer, _mlp, _read_actor, _save_actor
20from .rollout import _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
21from .search import NeuralMAPElites
22from .td3 import (_bellman_target, _checked_step, _critic, _critic_loss, _polyak, OffPolicyStats, TD3Config)
23
24
25class _TeamNetwork(nn.Module):
26 def __init__(self, count, obs_size, act_size, config, seed, device):
27 super().__init__()
28 self.count, self.obs_size = count, obs_size
29 rng = np.random.default_rng(seed)
30 sizes = config.hidden_sizes
31 if sizes:
32 self.trunk = nn.Sequential(_mlp(obs_size, sizes[-1], PolicyConfig(sizes[:-1]),
33 _seed(rng), device, nn.ReLU), nn.ReLU())
34 else:
35 self.trunk = nn.Identity()
36 self.heads = nn.ModuleList(_mlp(sizes[-1] if sizes else obs_size, act_size, PolicyConfig(()),
37 _seed(rng), device) for _ in range(count))
38
39 def forward(self, observations):
40 observations = observations.unflatten(-1, (self.count, self.obs_size))
41 hidden = self.trunk(observations)
42 return torch.cat([head(hidden[..., role, :]) for role, head in enumerate(self.heads)], dim=-1)
43
44 def local(self, observations, role):
45 return self.heads[role](self.trunk(observations)).tanh()
46
47
48
50 """Act on a joint Box observation in fixed agent order.
51
52 The observation and action Boxes each start with the same agent axis.
53 All agents have the same number of observation and action coordinates.
54 Action bounds may differ by agent. Hidden layers are shared and the
55 final affine action head is specific to each role.
56 """
57
58 _artifact_kind = "masqd-team"
59
60 def __init__(self, observation_space, action_space, *, config=None, seed=0, device="cpu"):
61 super().__init__(observation_space, action_space, config=config, seed=seed, device=device)
62
63 def _build_network(self, outputs, seed):
64 shape, actions = self._obs_shape, self._actions.shape
65 if len(shape) < 2 or len(actions) < 2 or shape[0] < 2 or shape[0] != actions[0]:
66 raise ValueError("Use joint Box observations and actions with the same leading agent axis.")
67 return _TeamNetwork(shape[0], prod(shape[1:]), outputs // shape[0], self.config, seed, self.device)
68
69
70 def save(self, path):
71 """Save the team with its joint observation and action layouts."""
72 _save_actor(path, dict(version=1, kind=self._artifact_kind, observation_shape=self._obs_shape,
73 action_shape=self._actions.shape, low=self._actions.low, high=self._actions.high,
74 dtype=self._actions.dtype, hidden_sizes=self.config.hidden_sizes),
75 self._parameters())
76
77
78 @classmethod
79 def load(cls, path, *, device="cpu"):
80 """Return a deployable deterministic TeamPolicy."""
81 metadata, parameters = _read_actor(path)
82 if metadata.get("version") != 1 or metadata.get("kind") != cls._artifact_kind:
83 raise ValueError(f"Unsupported {cls.__name__} policy artifact.")
84 shape = tuple(_integer(size, "Observation extent") for size in metadata["observation_shape"])
85 layout = _BoxLayout(tuple(_integer(size, "Action extent") for size in metadata["action_shape"]),
86 tuple(metadata["low"]), tuple(metadata["high"]), metadata["dtype"])
87 actor = cls._from_layout(shape, layout, PolicyConfig(tuple(metadata["hidden_sizes"])),
88 0, device, stochastic=False)
89 actor._set_parameters(parameters)
90 return actor
91
92
93
94@dataclass(frozen=True)
96 """Report completed generations, reanchors, replay updates and truncated prefixes."""
97
98 generations: int = 0
99 anchors: int = 0
100 discarded_prefix_steps: int = 0
101
102
104 def __init__(self, actor, config, dimensions, length_scale, seed, counts):
105 self.actor, self.config, self.counts = actor, config, counts
106 self.rng = np.random.default_rng(seed)
107 self.torch_rng = torch.Generator(device=actor.device).manual_seed(_seed(self.rng))
108 self.replay = _ConditionedReplay(config.replay_capacity, actor, dimensions, length_scale)
109 net = actor._network
110 self.size, self.act_size = net.obs_size, prod(actor._actions.shape[1:])
111 self.critics = nn.ModuleList(nn.ModuleList(_mlp(self.size + dimensions + self.act_size, 1,
112 PolicyConfig(config.critic_hidden_sizes),
113 _seed(self.rng), actor.device, nn.ReLU)
114 for _ in range(2)) for _ in range(net.count))
115 self.targets = deepcopy(self.critics).requires_grad_(False)
116 self.target_actor = deepcopy(net).requires_grad_(False)
117 self.optimizer = torch.optim.Adam(self.critics.parameters(), lr=config.critic_learning_rate)
118 self.actor_optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=config.actor_learning_rate)
119 self.steps = 0
120
121 def record(self, episode, achieved, target, relabel_probability):
122 position = self.replay.position
123 proposal = _Proposal(_Operator.PG if target is not None else _Operator.RANDOM, None, target)
124 self.replay.add_episode(episode, achieved, proposal)
125 if target is not None:
126 count = min(self.replay.capacity, episode.steps)
127 rows = (position + np.arange(episode.steps - count, episode.steps)) % self.replay.capacity
128 relabel = self.rng.random(count) < relabel_probability
129 self.replay.targets[rows[relabel]] = achieved
130
131 def _batch(self, role):
132 replay = self.replay
133 observations, actions, rewards, successors, terminated = replay.sample(
134 self.config.batch_size, self.rng, self.actor.device)
135 start = role * self.size
136 state = slice(start, start + self.size)
137 start = role * self.act_size
138 action = slice(start, start + self.act_size)
139 label = observations[:, -replay.targets.shape[1]:]
140 return observations[:, state], actions[:, action], rewards, successors[:, state], terminated, label
141
142 def _actor_update(self, actor, optimizer, target=None):
143 objective = []
144 for role, critics in enumerate(self.critics):
145 state, _, _, _, _, goals = self._batch(role)
146 if target is not None:
147 goals = actor._tensor(target).expand(len(state), -1)
148 value = _critic(critics[0], torch.cat((state, goals), dim=-1),
149 actor._network.local(state, role))
150 objective.append(-value.mean())
151 loss = torch.stack(objective).mean()
152 if not torch.isfinite(loss):
153 raise ValueError("MASQD produced a nonfinite actor loss.")
154 parameters = actor._trainable_parameters()
155 for parameter, grad in zip(parameters, torch.autograd.grad(loss, parameters)):
156 parameter.grad = grad
157 _checked_step(optimizer)
158 self.counts["optimizer_steps"] += 1
159
160 def update(self):
161 config = self.config
162 losses = []
163 for role, (critics, targets) in enumerate(zip(self.critics, self.targets)):
164 state, action, rewards, successor, terminated, goal = self._batch(role)
165 with torch.no_grad():
166 noise = torch.randn(action.shape, generator=self.torch_rng, device=action.device)
167 noise = (noise * config.target_noise).clamp(-config.noise_clip, config.noise_clip)
168 next_actions = (self.target_actor.local(successor, role) + noise).clamp(-1, 1)
169 next_input = torch.cat((successor, goal), dim=-1)
170 first, second = (_critic(critic, next_input, next_actions) for critic in targets)
171 value = _bellman_target(rewards, terminated, first, second, config.gamma)
172 losses.append(_critic_loss(critics, torch.cat((state, goal), dim=-1), action, value))
173 self.optimizer.zero_grad(set_to_none=True)
174 torch.stack(losses).mean().backward()
175 _checked_step(self.optimizer)
176 self.steps += 1
177 self.counts["critic_updates"] += 1
178 self.counts["optimizer_steps"] += 1
179 if self.steps % config.policy_delay == 0:
180 self._actor_update(self.actor, self.actor_optimizer)
181 self.counts["actor_updates"] += 1
182 _polyak(self.actor._network, self.target_actor, config.tau)
183 _polyak(self.critics, self.targets, config.tau)
184
185 def refine(self, parameters, target, steps):
186 actor = self.actor._new(0)
187 actor._set_parameters(parameters)
188 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=self.config.actor_learning_rate)
189 for _ in range(steps):
190 self._actor_update(actor, optimizer, target)
191 self.counts["policy_gradient_steps"] += 1
192 return actor._parameters()
193
194
195
197 """Run MASQD on joint continuous observations and actions.
198
199 Use a Gymnasium environment that returns one team reward per step.
200 The first axis of its observation and action Boxes identifies agents.
201 Team rewards must be nonnegative for exponential similarity shaping.
202 The same transitions feed independent role-specific TD3 minibatches.
203
204 :param env_factory: Factory for a single joint Gymnasium environment.
205 :param archive: Empty best-only Grid or CVTGrid that maximizes team return.
206 :param descriptor: Function of a completed team Episode.
207 :param td3: Optional TD3Config for all role critics and the target actor.
208 :param population_size: Even number of policies in a CEM population.
209 :param warmup_generations: Number of CEM batches evaluated before updates.
210 :param anchor_interval: Generations between resets to a randomly sampled elite.
211 :param initial_sigma: Per-parameter Gaussian standard deviation after reanchoring.
212 :param minimum_sigma: Standard-deviation floor for the diagonal CEM distribution.
213 :param descriptor_sigma: Reanchoring noise in normalized descriptor units.
214 :param gradient_steps: Policy-gradient updates per refined team. Zero runs CEM only.
215 :param critic_steps: TD3 updates per generation after replay warm-up.
216 :param length_scale: Reward similarity length scale in normalized descriptor units.
217 :param relabel_probability: Probability of replacing the target with achieved behavior.
218 :param policy: Shared encoder widths as a PolicyConfig.
219 :param fitness: Optional episode-based fitness function. Defaults to team return.
220 :param evaluation_episodes: Number of complete episodes per measured team.
221 :param max_episode_steps: Per-episode safety horizon.
222 :param seed: Nonnegative search, network, and simulator reset seed.
223 :param device: CPU or CUDA Torch device.
224 :param on_step: Optional callback receiving the archive and cumulative stats.
225 """
226
227 def __init__(self, env_factory, archive, *, descriptor, td3=None, population_size=16,
228 warmup_generations=1, anchor_interval=5, initial_sigma=.1, minimum_sigma=.01,
229 descriptor_sigma=.1, gradient_steps=4, critic_steps=16, length_scale=.25,
230 relabel_probability=.8, policy=None, fitness=None, evaluation_episodes=1,
231 max_episode_steps=300, seed=0, device="cpu", on_step=None):
232 self.population_size = _integer(population_size, "population_size", 2)
233 if self.population_size % 2:
234 raise ValueError("Use an even MASQD population_size.")
235 self.warmup_generations = _integer(warmup_generations, "warmup_generations", 0)
236 self.anchor_interval = _integer(anchor_interval, "anchor_interval")
237 self.gradient_steps = _integer(gradient_steps, "gradient_steps", 0)
238 self.critic_steps = _integer(critic_steps, "critic_steps")
239 if (not 0 < minimum_sigma <= initial_sigma < np.inf or not 0 <= descriptor_sigma < np.inf
240 or not 0. < length_scale < np.inf or not 0. <= relabel_probability <= 1.):
241 raise ValueError("Use finite CEM and descriptor scales, and a relabel probability in [0, 1].")
242 config = TD3Config() if td3 is None else td3
243 if not isinstance(config, TD3Config):
244 raise TypeError("td3 must be a TD3Config.")
245 self._domain = _DescriptorDomain(archive.features_domain)
246 super().__init__(env_factory, archive, descriptor=descriptor, policy=policy, fitness=fitness,
247 evaluation_episodes=evaluation_episodes, max_episode_steps=max_episode_steps,
248 seed=seed, device=device, on_step=on_step)
249 self.initial_sigma, self.minimum_sigma, self.descriptor_sigma = initial_sigma, minimum_sigma, descriptor_sigma
250 self.relabel_probability = relabel_probability
251 self._mean = self._actor._parameters().astype(float)
252 self._sigma = np.full(self._mean.shape, initial_sigma)
253 self._goal = np.zeros(len(self._domain.bounds), dtype=np.float32)
254 self._learner = self._make_team_learner(config, length_scale)
255 self._queue, self._scored = deque(), []
256 self._weights = np.log(self.population_size / 2 + .5) - np.log(np.arange(1, self.population_size // 2 + 1))
257 self._weights /= self._weights.sum()
258
259 def _build_actor(self, env, config, seed, device):
260 return TeamPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
261
262 def _make_team_learner(self, config, length_scale):
263 return _TeamLearner(self._actor._new(_seed(self._training_rng)), config,
264 len(self._domain.bounds), length_scale, _seed(self._training_rng), self._counts)
265
266 def _refine_team(self, parameters):
267 return self._learner.refine(parameters, self._goal, self.gradient_steps), self._goal.copy()
268
269 def _fit_team_distribution(self, policies):
270 variance = self._weights @ ((policies - self._mean) ** 2)
271 self._mean = self._weights @ policies
272 self._sigma = np.maximum(np.sqrt(variance), self.minimum_sigma)
273
274 @property
275 def stats(self):
276 """Return cumulative interactions, optimizer counts, and completed generations."""
277 return MASQDStats(**self._counts, replay_size=self._learner.replay.size)
278
279 def _start(self):
280 generation = self._counts["generations"]
281 warmup = generation < self.warmup_generations
282 if not warmup and len(self.archive) and (generation - self.warmup_generations) % self.anchor_interval == 0:
283 anchor = self.archive[self._training_rng.integers(len(self.archive))]
284 self._mean = np.asarray(anchor, dtype=float)
285 self._goal = self._domain.normalize(anchor.features.values, goal=True)
286 self._goal = np.clip(self._goal + self._training_rng.normal(
287 scale=self.descriptor_sigma, size=len(self._goal)), -1., 1.).astype(np.float32)
288 self._sigma.fill(self.initial_sigma)
289 self._counts["anchors"] += 1
290 config = self._learner.config
291 ready = (self.gradient_steps and not warmup and len(self.archive)
292 and self._learner.replay.size >= config.batch_size
293 and self._counts["evaluation_steps"] >= config.learning_starts)
294 if ready:
295 for _ in range(self.critic_steps):
296 self._learner.update()
297 for i, parameters in enumerate(self._training_rng.normal(
298 self._mean, self._sigma, size=(self.population_size, len(self._mean)))):
299 refined = ready and i >= self.population_size // 2
300 if refined:
301 parameters, target = self._refine_team(parameters)
302 else:
303 target = None
304 self._queue.append((parameters.astype(np.float32), target))
305
306 def _finish(self):
307 generation = self._counts["generations"]
308 if generation >= self.warmup_generations:
309 selected = sorted(self._scored, key=lambda item: item[0], reverse=True)[:len(self._weights)]
310 policies = np.stack([parameters for _, parameters in selected]).astype(float)
311 self._fit_team_distribution(policies)
312 self._scored.clear()
313 self._counts["generations"] += 1
314
315
316 def train(self, max_env_steps):
317 """Resume queued policies. Retry a cut candidate from a fresh reset."""
318 budget = _StepBudget(max_env_steps, self._counts)
319 with _open_environment(self._factory) as env:
320 _check_spaces(env, self._actor)
321 cursor = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
322 while budget.remaining:
323 if not self._queue:
324 self._start()
325 parameters, target = self._queue[0]
326 self._actor._set_parameters(parameters)
327 self._counts["candidate_attempts"] += 1
328 before = budget.remaining
329 episodes = []
330 for _ in range(self._episodes):
331 episode = _evaluate_episode(cursor, self._actor, budget)
332 if episode is None:
333 break
334 episodes.append(episode)
335 if len(episodes) < self._episodes:
336 self._counts["discarded_prefix_steps"] += before - budget.remaining
337 break
338 descriptors = [np.asarray(self._descriptor(episode), dtype=float) for episode in episodes]
339 quality = float(np.mean([episode.return_ if self._fitness is None else self._fitness(episode)
340 for episode in episodes]))
341 achieved_descriptors = [self._domain.normalize(descriptor) for descriptor in descriptors]
342 if not np.isfinite(quality):
343 raise ValueError("MASQD fitness must be finite.")
344 if self.gradient_steps:
345 for episode, achieved in zip(episodes, achieved_descriptors):
346 self._learner.record(episode, achieved, target, self.relabel_probability)
347 self._offer(episodes, "masqd" if target is not None else "team-cem",
348 descriptors=descriptors, quality=quality)
349 self._counts["evaluated_policies"] += 1
350 self._counts["pg_offspring"] += int(target is not None)
351 self._scored.append((quality, parameters))
352 self._queue.popleft()
353 if not self._queue:
354 self._finish()
355 if self._on_step is not None:
356 self._on_step(self.archive, self.stats)
357 return self.stats
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
_make_team_learner(self, config, length_scale)
Definition masqd.py:262
train(self, max_env_steps)
Run team evaluations under an additional hard environment-step cap.
Definition masqd.py:316
_fit_team_distribution(self, policies)
Definition masqd.py:269
_refine_team(self, parameters)
Definition masqd.py:266
A shared observation encoder and a distinct deterministic head per team role.
Definition masqd.py:49
load(cls, path, *, device="cpu")
Load a team independently of its original simulator and trainer.
Definition masqd.py:79
save(self, path)
Write a versioned numeric checkpoint of the shared encoder and role heads.
Definition masqd.py:70
_actor_update(self, actor, optimizer, target=None)
Definition masqd.py:142
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
_from_layout(cls, obs_shape, actions, config, seed, device, **kwargs)
Definition policy.py:161
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Definition search.py:24
_offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None)
Definition search.py:119
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25