29 """Set two distinct budgets, real environment steps and extra learner updates.
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.
45 replay_capacity: int = 50_000
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
54 exploration_noise: float = .15
55 extra_updates: int = 4
56 allocation: str =
"curiosity"
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))
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.")
69 raise ValueError(
"Invalid discount, target mixing, or exploration noise.")
73 def __init__(self, count, observation_size, action_size, config, seed, device):
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)
82 def forward(self, observations):
84 return torch.cat([actor(local[..., role, :])
for role, actor
in enumerate(self.
actors)], dim=-1)
128 def __init__(self, actor, config, seed, counts):
130 self.
rng, self.
allocation_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
131 self.
roles = actor._network.count
133 self.
actions = prod(actor._actions.shape)
135 self.
target_actor = deepcopy(actor._network).requires_grad_(
False)
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)
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)
155 def _update(self, role, batch):
156 states, actions, rewards, successors, terminal = batch
160 with torch.no_grad():
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
169 local = states.reshape(len(states), self.
roles, -1)
170 actors = self.
actor._network.actors
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)
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
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)
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)
201 _checked_step(optimizer)
202 self.
counts[
"rnd_updates"] += 1
203 self.
counts[
"optimizer_steps"] += 1
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):
210 self.
counts[
"learning_episodes"] += 1
215 """Train independent actors with centralized critics before each QD stage.
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.
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.
231 def __init__(self, env_factory, archive, *, descriptor, config=None, population_size=4, **kwargs):
232 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
234 if not isinstance(self.
config, MADECMConfig):
235 raise TypeError(
"config must be MADECMConfig.")
241 def _build_actor(self, env, config, seed, device):
242 return MADECMPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
246 """Return cumulative learning and archive accounting."""
249 role_updates=tuple(map(int, learner.role_updates)),
250 extra_role_updates=tuple(map(int, learner.extra_role_updates)))
252 def _collect(self, cursor, budget):
254 actor = learner.actor
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)
261 with torch.no_grad():
262 normalized = actor._normalized(actor._tensor(state)).cpu().numpy()
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:
276 """Reserve the horizon of each rollout and resume between complete stages."""
277 limit = _integer(max_env_steps,
"max_env_steps", 0)
282 with _open_environment(self.
_factory)
as env:
283 _check_spaces(env, self.
_actor)
286 while budget.remaining:
288 if budget.remaining < self.
_horizon:
292 if budget.remaining < evaluation_limit:
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")