QDpy
Loading...
Searching...
No Matches
madecm.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""A cooperative MADECM-style variant for joint Gymnasium Box environments."""
7
8from copy import deepcopy
9from dataclasses import dataclass
10from math import prod
11
12import numpy as np
13import torch
14from torch import nn
15from torch.nn import functional as F
16
17from .masqd import TeamPolicy
18from .policy import PolicyConfig, _integer, _mlp
19from .rollout import _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
20from .search import NeuralMAPElites
21from .td3 import OffPolicyStats, _Replay, _checked_step, _critic, _polyak
22
23__all__ = ["MADECM", "MADECMConfig", "MADECMPolicy", "MADECMStats"]
24
25
26
27@dataclass(frozen=True, slots=True)
29 """Set two distinct budgets, real environment steps and extra learner updates.
30
31 :param replay_capacity: Maximum joint transitions in FIFO replay.
32 :param batch_size: Joint transitions sampled per role update.
33 :param learning_starts: Random exploration steps before learning.
34 :param critic_hidden_sizes: ReLU hidden widths of each centralized critic and RND model.
35 :param actor_learning_rate: Adam learning rate for each local actor.
36 :param critic_learning_rate: Adam learning rate for each centralized critic.
37 :param curiosity_learning_rate: Adam learning rate for each local novelty predictor.
38 :param gamma: Discount of team rewards.
39 :param tau: Fraction of online parameters mixed into target networks.
40 :param exploration_noise: Gaussian deviation in normalized rollout actions.
41 :param extra_updates: Fixed total extra role updates per completed learning episode.
42 :param allocation: "curiosity" for novelty-driven allocation or "uniform" for the control.
43 """
44
45 replay_capacity: int = 50_000
46 batch_size: int = 64
47 learning_starts: int = 128
48 critic_hidden_sizes: tuple[int, ...] = (64, 64)
49 actor_learning_rate: float = .001
50 critic_learning_rate: float = .001
51 curiosity_learning_rate: float = .001
52 gamma: float = .99
53 tau: float = .01
54 exploration_noise: float = .15
55 extra_updates: int = 4
56 allocation: str = "curiosity"
57
58 def __post_init__(self):
59 for name in ("replay_capacity", "batch_size", "learning_starts", "extra_updates"):
60 minimum = int(name in ("replay_capacity", "batch_size"))
61 object.__setattr__(self, name, _integer(getattr(self, name), name, minimum))
62 object.__setattr__(self, "critic_hidden_sizes", PolicyConfig(self.critic_hidden_sizes).hidden_sizes)
63 if not self.batch_size <= self.replay_capacity or self.allocation not in ("curiosity", "uniform"):
64 raise ValueError("Use batch_size <= replay_capacity and curiosity or uniform allocation.")
65 for name in ("actor_learning_rate", "critic_learning_rate", "curiosity_learning_rate"):
66 if not 0 < getattr(self, name) < np.inf:
67 raise ValueError(f"{name} must be positive and finite.")
68 if not (0 <= self.gamma <= 1 and 0 < self.tau <= 1 and 0 <= self.exploration_noise < np.inf):
69 raise ValueError("Invalid discount, target mixing, or exploration noise.")
70
71
72class _LocalNetwork(nn.Module):
73 def __init__(self, count, observation_size, action_size, config, seed, device):
74 super().__init__()
75 self.count = count
76 self.observation_size = observation_size
77 rng = np.random.default_rng(seed)
78 self.actors = nn.ModuleList(
79 _mlp(observation_size, action_size, config, _seed(rng), device, nn.ReLU) for _ in range(count)
80 )
81
82 def forward(self, observations):
83 local = observations.unflatten(-1, (self.count, self.observation_size))
84 return torch.cat([actor(local[..., role, :]) for role, actor in enumerate(self.actors)], dim=-1)
85
86
87
89 """Use each role's local observation to compute its bounded action.
90
91 The inherited numeric checkpoint helpers preserve this actor layout.
92 Centralized critics and curiosity predictors are needed only in training.
93 """
94
95 _artifact_kind = "madecm-team"
96
97 def _build_network(self, outputs, seed):
98 shape, actions = self._obs_shape, self._actions.shape
99 if len(shape) < 2 or len(actions) < 2 or shape[0] < 2 or shape[0] != actions[0]:
100 raise ValueError("Use joint Box observations and actions with the same leading agent axis.")
101 return _LocalNetwork(shape[0], prod(shape[1:]), outputs // shape[0], self.config, seed, self.device)
102
103
104
105@dataclass(frozen=True)
107 """Count role critic, actor, and novelty updates separately from simulator steps."""
108
109 rounds: int = 0
110 learning_episodes: int = 0
111 rnd_updates: int = 0
112 role_updates: tuple[int, ...] = ()
113 extra_role_updates: tuple[int, ...] = ()
114
115
116def _update_allocation(errors, extra, mode, rng):
117 if not np.isfinite(errors).all():
118 raise ValueError("MADECM produced nonfinite local novelty.")
119 total = errors.sum()
120 if mode == "uniform" or not total:
121 probabilities = np.full(len(errors), 1. / len(errors))
122 else:
123 probabilities = errors / total
124 return rng.multinomial(extra, probabilities)
125
126
128 def __init__(self, actor, config, seed, counts):
129 self.actor, self.config, self.counts = actor, config, counts
130 self.rng, self.allocation_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
131 self.roles = actor._network.count
132 self.observations = prod(actor._obs_shape)
133 self.actions = prod(actor._actions.shape)
134 self.replay = _Replay(config.replay_capacity, self.observations, self.actions)
135 self.target_actor = deepcopy(actor._network).requires_grad_(False)
136 widths = PolicyConfig(config.critic_hidden_sizes)
137
138 def models(inputs, outputs):
139 return nn.ModuleList(
140 _mlp(inputs, outputs, widths, _seed(self.rng), actor.device, nn.ReLU) for _ in range(self.roles)
141 )
142
143 self.critics = models(self.observations + self.actions, 1)
144 self.targets = deepcopy(self.critics).requires_grad_(False)
145 self.predictors = models(actor._network.observation_size, 8)
146 self.rnd_targets = models(actor._network.observation_size, 8).requires_grad_(False)
147 self.actor_opts = [torch.optim.Adam(net.parameters(), lr=config.actor_learning_rate)
148 for net in actor._network.actors]
149 self.critic_opts = [torch.optim.Adam(net.parameters(), lr=config.critic_learning_rate) for net in self.critics]
150 self.rnd_opts = [torch.optim.Adam(net.parameters(), lr=config.curiosity_learning_rate)
151 for net in self.predictors]
152 self.role_updates = np.zeros(self.roles, dtype=np.int64)
153 self.extra_role_updates = np.zeros_like(self.role_updates)
154
155 def _update(self, role, batch):
156 states, actions, rewards, successors, terminal = batch
157 config = self.config
158 critic = self.critics[role]
159 critic_opt = self.critic_opts[role]
160 with torch.no_grad():
161 next_actions = self.target_actor(successors).tanh()
162 target = _critic(self.targets[role], successors, next_actions).masked_fill(terminal, 0.)
163 target = rewards + config.gamma * target
164 critic_opt.zero_grad(set_to_none=True)
165 F.mse_loss(_critic(critic, states, actions), target).backward()
166 _checked_step(critic_opt)
167 self.counts["critic_updates"] += 1
168
169 local = states.reshape(len(states), self.roles, -1)
170 actors = self.actor._network.actors
171 # Replay actions fix the other agents' behavior for this actor's gradient.
172 joint_actions = list(actions.chunk(self.roles, dim=-1))
173 joint_actions[role] = actors[role](local[:, role]).tanh()
174 joint = torch.cat(joint_actions, dim=-1)
175 actor_opt = self.actor_opts[role]
176 actor_opt.zero_grad(set_to_none=True)
177 loss = -_critic(critic, states, joint).mean()
178 if not torch.isfinite(loss):
179 raise ValueError("MADECM produced a nonfinite actor loss.")
180 parameters = tuple(actors[role].parameters())
181 for parameter, gradient in zip(parameters, torch.autograd.grad(loss, parameters)):
182 parameter.grad = gradient
183 _checked_step(actor_opt)
184 _polyak(actors[role], self.target_actor.actors[role], config.tau)
185 _polyak(critic, self.targets[role], config.tau)
186 self.counts["actor_updates"] += 1
187 self.counts["optimizer_steps"] += 2
188 self.role_updates[role] += 1
189
190 def learn(self):
191 config = self.config
192 batch = self.replay.sample(config.batch_size, self.rng, self.actor.device)
193 local = batch[3].reshape(len(batch[3]), self.roles, -1)
194 errors = np.empty(self.roles)
195 for role, (predictor, target, optimizer) in enumerate(zip(self.predictors, self.rnd_targets, self.rnd_opts)):
196 prediction = predictor(local[:, role])
197 loss = F.mse_loss(prediction, target(local[:, role]))
198 errors[role] = float(loss.detach())
199 optimizer.zero_grad(set_to_none=True)
200 loss.backward()
201 _checked_step(optimizer)
202 self.counts["rnd_updates"] += 1
203 self.counts["optimizer_steps"] += 1
204 self._update(role, batch)
205 allocation = _update_allocation(errors, config.extra_updates, config.allocation, self.allocation_rng)
206 for role, count in enumerate(allocation):
207 for _ in range(count):
208 self._update(role, self.replay.sample(config.batch_size, self.rng, self.actor.device))
209 self.extra_role_updates += allocation
210 self.counts["learning_episodes"] += 1
211
212
213
215 """Train independent actors with centralized critics before each QD stage.
216
217 Each round collects one noisy learning episode, then evaluates the
218 learned team and genetically varied archive teams. Random network
219 distillation allocates a fixed number of extra updates across roles.
220 Archive fitness uses the caller's episode fitness or raw team return.
221 Archived actors can be exported without critics or curiosity models.
222
223 :param env_factory: Factory for a cooperative joint Box Gymnasium environment.
224 :param archive: Empty best-only Grid or CVTGrid maximizing episode fitness.
225 :param descriptor: Callable mapping an evaluation Episode to its descriptor.
226 :param config: MADECMConfig for replay and actor-critic updates.
227 :param population_size: Teams evaluated per round, including the learned team.
228 :param kwargs: Common NeuralMAPElites options including policy and episode horizon.
229 """
230
231 def __init__(self, env_factory, archive, *, descriptor, config=None, population_size=4, **kwargs):
232 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
233 self.config = MADECMConfig() if config is None else config
234 if not isinstance(self.config, MADECMConfig):
235 raise TypeError("config must be MADECMConfig.")
236 self._population_size = _integer(population_size, "population_size")
237 self._learner = _Learner(self._new_actor(_seed(self._actor_rng)), self.config,
238 _seed(self._training_rng), self._counts)
240
241 def _build_actor(self, env, config, seed, device):
242 return MADECMPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
243
244 @property
245 def stats(self):
246 """Return cumulative learning and archive accounting."""
247 learner = self._learner
248 return MADECMStats(**self._counts, replay_size=learner.replay.size,
249 role_updates=tuple(map(int, learner.role_updates)),
250 extra_role_updates=tuple(map(int, learner.extra_role_updates)))
251
252 def _collect(self, cursor, budget):
253 learner = self._learner
254 actor = learner.actor
255 cursor.reset()
256 while not cursor.ended:
257 state = cursor.observation
258 if self._counts["training_steps"] < self.config.learning_starts:
259 normalized = self._training_rng.uniform(-1, 1, size=learner.actions)
260 else:
261 with torch.no_grad():
262 normalized = actor._normalized(actor._tensor(state)).cpu().numpy()
263 normalized = normalized + self._training_rng.normal(0., self.config.exploration_noise,
264 size=learner.actions)
265 action = actor._decode(np.clip(normalized, -1., 1.))
266 encoded = actor._encode(action)
267 reward, terminal, _, _ = cursor.step(action, budget, "training_steps")
268 learner.replay.add(state, encoded, reward, cursor.observation, terminal)
269 if learner.replay.size and self._counts["training_steps"] >= self.config.learning_starts:
270 learner.learn()
271
272
275 def train(self, max_env_steps):
276 """Reserve the horizon of each rollout and resume between complete stages."""
277 limit = _integer(max_env_steps, "max_env_steps", 0)
278 if not limit:
279 return self.stats
280 budget = _StepBudget(limit, self._counts)
281 evaluation_limit = self._episodes * self._horizon
282 with _open_environment(self._factory) as env:
283 _check_spaces(env, self._actor)
284 training = _Cursor(env, self._learner.actor, self._horizon, self._training_rng)
285 evaluation = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
286 while budget.remaining:
288 if budget.remaining < self._horizon:
289 break
290 self._collect(training, budget)
291 self._evaluated_in_round = 0
292 if budget.remaining < evaluation_limit:
293 break
294 first = self._evaluated_in_round == 0
295 parameters = self._learner.actor._parameters() if first else self._genetic_parameters()
296 self._actor._set_parameters(parameters)
297 self._counts["candidate_attempts"] += 1
298 self._counts["actor_injections"] += int(first)
299 episodes = [_evaluate_episode(evaluation, self._actor, budget) for _ in range(self._episodes)]
300 self._counts["evaluated_policies"] += 1
301 self._offer(episodes, "maddpg" if first else "genetic")
302 self._evaluated_in_round += 1
304 self._counts["rounds"] += 1
305 if self._on_step is not None:
306 self._on_step(self.archive, self.stats)
307 return self.stats
Replay, optimizer and curiosity settings for cooperative MADECM.
Definition madecm.py:28
A deployable team with one independent local actor per role.
Definition madecm.py:88
Record complete training and archive stages and how curiosity allocated updates.
Definition madecm.py:106
Alternate local curiosity training with measured MAP-Elites team variation.
Definition madecm.py:214
train(self, max_env_steps)
Spend additional environment steps in complete rollout and policy evaluations.
Definition madecm.py:275
_collect(self, cursor, budget)
Definition madecm.py:252
_update(self, role, batch)
Definition madecm.py:155
A shared observation encoder and a distinct deterministic head per team role.
Definition masqd.py:49
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
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
_new_actor(self, seed, device=None)
Definition search.py:112
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76