5"""Small reproducible cooperative-control and offline policy-generation studies."""
9from pathlib
import Path
11from time
import perf_counter
13import gymnasium
as gym
20from qdpy.rl import (ContinuousPolicy, MASQD, PolicyConfig, PolicyDiffusion,
21 PolicyDiffusionConfig, TD3Config, evaluate_skills)
26 """Expose matching leading agent axes and a single nonnegative team reward."""
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)
31 def __init__(self, weak=False):
34 def reset(self, *, seed=None, options=None):
35 super().reset(seed=seed)
37 self.
target = float(self.np_random.uniform(-.8, .8))
41 def step(self, action):
43 raise ValueError(
"Expected two bounded continuous actions.")
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, {}
51def _roll_team(act, seed, weak=False):
53 observation, _ = env.reset(seed=seed)
54 actions, rewards = [], []
56 action = act(observation)
57 observation, reward, _, _, _ = env.step(action)
58 actions.append(action[:, 0].copy())
59 rewards.append(reward)
61 return float(sum(rewards)), tuple(np.mean(actions, axis=0))
65 return Grid(shape=(7, 7), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 8.),),
66 fitness_weights=(1.,))
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())
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)])
82 algorithm =
MixME(archive, budget // 4, (count, count), role_bounds=((-1., 1.),) * 2,
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)])
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.")
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)
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)
134 """Supply an independent reset target to the controller at every rollout."""
136 observation_space = gym.spaces.Box(-1., 1., (1,), np.float32)
137 action_space = gym.spaces.Box(-1., 1., (1,), np.float32)
139 def reset(self, *, seed=None, options=None):
140 super().reset(seed=seed)
142 self.
target = np.array([self.np_random.uniform(-.8, .8)], dtype=np.float32)
143 return self.
target.copy(), {}
145 def step(self, action):
147 return self.
target.copy(), 2. - abs(float(action[0] - self.
target[0])), self.
t == 4,
False, {}
150def _teacher_archive():
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))]
158 return environment, config, archive
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)
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)
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()
179 for i, goal
in enumerate(goals):
180 if method ==
"diffusion":
181 instances[goal] = restored.sample_policy(goal, seed=40_000 + seed * 100 + i)
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)
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))
216 print(json.dumps(row))
219if __name__ ==
"__main__":
Evolve whole teams with within-role policy variation and team crossover.
:param obj: Slice indicating on which objectives the domination is tested.
Learn diverse teams with diagonal CEM, archive reanchoring, and per-role TD3 critics.
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Architecture of the actor and, for PPO, the separate value network.
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.
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.