QDpy
Loading...
Searching...
No Matches
team_policy_reuse.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Small reproducible cooperative-control and offline policy-generation studies."""
6
7import argparse
8import json
9from pathlib import Path
10import random
11from time import perf_counter
12
13import gymnasium as gym
14import numpy as np
15import torch
16
17from qdpy.algorithms import MixME
18from qdpy.containers import Grid
19from qdpy.phenotype import Features, Fitness, Individual
20from qdpy.rl import (ContinuousPolicy, MASQD, PolicyConfig, PolicyDiffusion,
21 PolicyDiffusionConfig, TD3Config, evaluate_skills)
22
23
24
25class CooperativeBox(gym.Env):
26 """Expose matching leading agent axes and a single nonnegative team reward."""
27
28 observation_space = gym.spaces.Box(-1., 1., shape=(2, 2), dtype=np.float32)
29 action_space = gym.spaces.Box(-1., 1., shape=(2, 1), dtype=np.float32)
30
31 def __init__(self, weak=False):
32 self.weak = weak
33
34 def reset(self, *, seed=None, options=None):
35 super().reset(seed=seed)
36 self.tick = 0
37 self.target = float(self.np_random.uniform(-.8, .8))
38 self.observation = np.array([[self.target, -1.], [self.target, 1.]], dtype=np.float32)
39 return self.observation.copy(), {}
40
41 def step(self, action):
42 if not self.action_space.contains(action):
43 raise ValueError("Expected two bounded continuous actions.")
44 self.tick += 1
45 left, right = action[:, 0]
46 total = (left + (.3 if self.weak else 1.) * right) / 2
47 reward = 2. - abs(total - self.target) - .15 * abs(left - right)
48 return self.observation.copy(), float(reward), self.tick >= 4, False, {}
49
50
51def _roll_team(act, seed, weak=False):
52 env = CooperativeBox(weak)
53 observation, _ = env.reset(seed=seed)
54 actions, rewards = [], []
55 for _ in range(4):
56 action = act(observation)
57 observation, reward, _, _, _ = env.step(action)
58 actions.append(action[:, 0].copy())
59 rewards.append(reward)
60 env.close()
61 return float(sum(rewards)), tuple(np.mean(actions, axis=0))
62
63
64def _team_grid():
65 return Grid(shape=(7, 7), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 8.),),
66 fitness_weights=(1.,))
67
68
69def _mix_me(seed, budget, archive, config):
70 observation = gym.spaces.Box(-1., 1., shape=(2,), dtype=np.float32)
71 action = gym.spaces.Box(-1., 1., shape=(1,), dtype=np.float32)
72 count = len(ContinuousPolicy(observation, action, config=config)._parameters())
73
74 def team_for(vector):
75 roles = [ContinuousPolicy(observation, action, config=config) for _ in range(2)]
76 for i, role in enumerate(roles):
77 role._set_parameters(vector[i * count:(i + 1) * count])
78 return lambda joint: np.stack([actor.act(obs) for actor, obs in zip(roles, joint)])
79
80 random.seed(seed)
81 np.random.seed(seed)
82 algorithm = MixME(archive, budget // 4, (count, count), role_bounds=((-1., 1.),) * 2,
83 batch_size=1)
84 rng = np.random.default_rng(seed)
85 for _ in range(budget // 4):
86 candidate, = algorithm.ask_batch()
87 quality, features = _roll_team(team_for(candidate), int(rng.integers(2**32)))
88 algorithm.tell_batch([((quality,), features)])
89 return team_for
90
91
92
93def team_trial(seed, budget):
94 """Select the adaptation policy on one reset panel and audit it on another."""
95 if budget < 4 or budget % 4:
96 raise ValueError("Use a positive multiple of the four-step team horizon.")
97 config = PolicyConfig((8,))
98 for method in ("masqd", "team_cem", "mix_me"):
99 start = perf_counter()
100 archive = _team_grid()
101 critic_updates = refined = 0
102 if method == "mix_me":
103 decode = _mix_me(seed, budget, archive, config)
104 else:
105 learner = MASQD(CooperativeBox, archive,
106 descriptor=lambda episode: np.asarray(episode.actions).mean(axis=0).ravel(),
107 policy=config, population_size=8, anchor_interval=3,
108 td3=TD3Config(replay_capacity=4096, batch_size=24, learning_starts=24,
109 critic_hidden_sizes=(16,)),
110 gradient_steps=3 if method == "masqd" else 0, critic_steps=6,
111 initial_sigma=.28, seed=seed)
112 stats = learner.train(budget)
113 critic_updates, refined = stats.critic_updates, stats.pg_offspring
114 def decode(individual):
115 return learner.policy_for(individual).act
116 actors = [decode(individual) for individual in archive]
117 probe = [30_000 + seed * 10 + k for k in range(3)]
118 held = [80_000 + seed * 10 + k for k in range(5)]
119 def panel(act, seeds, weak):
120 return float(np.mean([_roll_team(act, value, weak)[0] for value in seeds]))
121 adapted = max(actors, key=lambda act: panel(act, probe, True))
122 test_nominal = panel(adapted, held, False)
123 test_damaged = panel(adapted, held, True)
124 yield dict(method=method, seed=seed, steps=budget, coverage=archive.filled_bins / 49,
125 qd_score=archive.qd_score(), best=archive.best.fitness.values[0],
126 critic_updates=critic_updates, refined=refined,
127 audit_steps=(len(actors) * len(probe) + 2 * len(held)) * 4,
128 adapted_nominal=test_nominal, adapted_weak=test_damaged,
129 elapsed_s=perf_counter() - start)
130
131
132
133class SkillBox(gym.Env):
134 """Supply an independent reset target to the controller at every rollout."""
135
136 observation_space = gym.spaces.Box(-1., 1., (1,), np.float32)
137 action_space = gym.spaces.Box(-1., 1., (1,), np.float32)
138
139 def reset(self, *, seed=None, options=None):
140 super().reset(seed=seed)
141 self.t = 0
142 self.target = np.array([self.np_random.uniform(-.8, .8)], dtype=np.float32)
143 return self.target.copy(), {}
144
145 def step(self, action):
146 self.t += 1
147 return self.target.copy(), 2. - abs(float(action[0] - self.target[0])), self.t == 4, False, {}
148
149
150def _teacher_archive():
151 environment = SkillBox()
152 config = PolicyConfig(())
153 archive = Grid(shape=(31,), features_domain=((-1., 1.),),
154 fitness_domain=((0., 8.),), fitness_weights=(1.,))
155 for goal in np.linspace(-.95, .95, 31):
156 weights = [0., float(np.arctanh(goal))]
157 archive.add(Individual(weights, fitness=Fitness((4.,), weights=(1.,)), features=Features((goal,))))
158 return environment, config, archive
159
160
161
162def diffusion_trial(seed, vae_epochs, diffusion_epochs, output):
163 """Fit only teacher parameters and descriptors, then evaluate sampled actors."""
164 env, policy, archive = _teacher_archive()
165 dataset = np.asarray([list(ind) for ind in archive], dtype=np.float32)
166 config = PolicyDiffusionConfig(latent_size=2, hidden_sizes=(24, 24), diffusion_steps=24)
167 model = PolicyDiffusion(env.observation_space, env.action_space, archive.features_domain,
168 policy=policy, config=config, seed=seed)
169 start = perf_counter()
170 stats = model.fit_archive(archive, vae_epochs=vae_epochs, diffusion_epochs=diffusion_epochs, batch_size=16)
171 output.parent.mkdir(parents=True, exist_ok=True)
172 model.save(output)
173 restored = PolicyDiffusion.load(output)
174 training_elapsed = perf_counter() - start
175 goals = [(x,) for x in np.linspace(-.8, .8, 10)]
176 for method in ("diffusion", "nearest"):
177 start = perf_counter()
178 instances = {}
179 for i, goal in enumerate(goals):
180 if method == "diffusion":
181 instances[goal] = restored.sample_policy(goal, seed=40_000 + seed * 100 + i)
182 else:
183 individual = min(archive, key=lambda ind: abs(ind.features.values[0] - goal[0]))
184 actor = ContinuousPolicy(env.observation_space, env.action_space, config=policy)
185 actor._set_parameters(individual)
186 instances[goal] = actor
187 audit = evaluate_skills(SkillBox, lambda obs, goal: instances[goal].act(obs), goals,
188 feature=lambda obs, action, info: action,
189 skill_bounds=archive.features_domain, archive=archive,
190 episodes=4, max_episode_steps=4, tolerance=.15, seed=1230 + seed)
191 yield dict(method=method, seed=seed, policies=stats.policies,
192 vae_updates=stats.vae_updates if method == "diffusion" else 0,
193 diffusion_updates=stats.diffusion_updates if method == "diffusion" else 0,
194 training_s=training_elapsed if method == "diffusion" else 0., audit_steps=audit.env_steps,
195 error=audit.mean_distance, coverage=audit.coverage, achieved_coverage=audit.archive_coverage,
196 qd_score=audit.archive_qd_score, mean_return=audit.mean_return,
197 bytes=output.stat().st_size if method == "diffusion" else dataset.nbytes,
198 elapsed_s=perf_counter() - start)
199
200
201def main():
202 """Print JSON records for a small CPU run and optionally write a model."""
203 parser = argparse.ArgumentParser(description=__doc__)
204 parser.add_argument("study", choices=("team", "diffusion"))
205 parser.add_argument("--seeds", type=int, nargs="+", default=[0])
206 parser.add_argument("--budget", type=int, default=512)
207 parser.add_argument("--vae-epochs", type=int, default=140)
208 parser.add_argument("--diffusion-epochs", type=int, default=300)
209 parser.add_argument("--output", type=Path, default=Path("policy-diffusion.npz"))
210 args = parser.parse_args()
211 torch.set_num_threads(1)
212 for seed in args.seeds:
213 records = (team_trial(seed, args.budget) if args.study == "team" else
214 diffusion_trial(seed, args.vae_epochs, args.diffusion_epochs, args.output))
215 for row in records:
216 print(json.dumps(row))
217
218
219if __name__ == "__main__":
220 main()
Evolve whole teams with within-role policy variation and team crossover.
Definition mix_me.py:23
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
Learn diverse teams with diagonal CEM, archive reanchoring, and per-role TD3 critics.
Definition masqd.py:196
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
Size the fixed-layout weight VAE and latent diffusion network.
Learn and deploy a conditional distribution of deterministic policy weights.
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25
Two agents control a joint action against a common target and role disturbance.
Single-agent test task with a measured mean action and seeded reward target.