26 def __init__(self, count, obs_size, act_size, config, seed, device):
29 rng = np.random.default_rng(seed)
30 sizes = config.hidden_sizes
33 _seed(rng), device, nn.ReLU), nn.ReLU())
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))
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)
44 def local(self, observations, role):
45 return self.
heads[role](self.
trunk(observations)).tanh()
104 def __init__(self, actor, config, dimensions, length_scale, seed, counts):
106 self.
rng = np.random.default_rng(seed)
107 self.
torch_rng = torch.Generator(device=actor.device).manual_seed(_seed(self.
rng))
110 self.
size, self.
act_size = net.obs_size, prod(actor._actions.shape[1:])
113 _seed(self.
rng), actor.device, nn.ReLU)
114 for _
in range(2))
for _
in range(net.count))
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)
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
131 def _batch(self, role):
133 observations, actions, rewards, successors, terminated = replay.sample(
135 start = role * self.
size
136 state = slice(start, start + self.
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
142 def _actor_update(self, actor, optimizer, target=None):
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
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()
177 self.
counts[
"critic_updates"] += 1
178 self.
counts[
"optimizer_steps"] += 1
179 if self.
steps % config.policy_delay == 0:
181 self.
counts[
"actor_updates"] += 1
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):
191 self.
counts[
"policy_gradient_steps"] += 1
192 return actor._parameters()
197 """Run MASQD on joint continuous observations and actions.
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.
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.
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):
234 raise ValueError(
"Use an even MASQD population_size.")
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.")
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)
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)
259 def _build_actor(self, env, config, seed, device):
260 return TeamPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
262 def _make_team_learner(self, config, length_scale):
266 def _refine_team(self, parameters):
269 def _fit_team_distribution(self, policies):
276 """Return cumulative interactions, optimizer counts, and completed generations."""
280 generation = self.
_counts[
"generations"]
284 self.
_mean = np.asarray(anchor, dtype=float)
285 self.
_goal = self.
_domain.normalize(anchor.features.values, goal=
True)
292 and self.
_learner.replay.size >= config.batch_size
293 and self.
_counts[
"evaluation_steps"] >= config.learning_starts)
304 self.
_queue.append((parameters.astype(np.float32), target))
307 generation = self.
_counts[
"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)
313 self.
_counts[
"generations"] += 1
317 """Resume queued policies. Retry a cut candidate from a fresh reset."""
319 with _open_environment(self.
_factory)
as env:
320 _check_spaces(env, self.
_actor)
322 while budget.remaining:
325 parameters, target = self.
_queue[0]
326 self.
_actor._set_parameters(parameters)
327 self.
_counts[
"candidate_attempts"] += 1
328 before = budget.remaining
331 episode = _evaluate_episode(cursor, self.
_actor, budget)
334 episodes.append(episode)
336 self.
_counts[
"discarded_prefix_steps"] += before - budget.remaining
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.")
345 for episode, achieved
in zip(episodes, achieved_descriptors):
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))