6"""Run optional continuous QD+RL baselines on a small asymmetric Box task."""
8from argparse
import ArgumentParser
9from dataclasses
import asdict, replace
11from pathlib
import Path
13import gymnasium
as gym
19 ContinuousPolicy, DCGMAPElites, DCRLMAPElites, DescriptorConditionedPolicy,
20 NeuralMAPElites, PGAMAPElites, PolicyConfig, PPO, PPOAssistedMAPElites, PPOConfig, QDPG, TD3, TD3Config,
25DEFAULT_METHODS = (
"ppo",
"td3",
"neural-map-elites",
"ppo-assisted-map-elites",
"pga-map-elites")
26CONDITIONED_METHODS = (
"dcg-map-elites",
"dcrl-map-elites",
"dcrl-no-injection")
27ALL_METHODS = (*DEFAULT_METHODS,
"qd-pg", *CONDITIONED_METHODS)
32 """Reward tracking a target velocity and record the resulting displacement."""
34 observation_space = gym.spaces.Box(-1, 1, (5,), dtype=np.float32)
35 action_space = gym.spaces.Box(np.array([-2., 1.], dtype=np.float32),
36 np.array([4., 5.], dtype=np.float32))
38 def _observation(self):
41 def reset(self, *, seed=None, options=None):
42 """Pick a seeded target and start at the origin."""
43 super().
reset(seed=seed)
45 self.
target = self.np_random.uniform([0.2, -0.7], [0.8, -0.1])
50 """Apply a velocity command and score its squared tracking error."""
52 raise ValueError(
"Invalid physical action.")
53 velocity = (np.asarray(action, dtype=np.float64) - [1., 3.]) / [3., 2.]
55 reward = 1 - np.mean(np.square(velocity - self.
target)) / 4
61def descriptor(episode):
62 return episode.observations[-1, :2]
66def state_descriptor(observation, info):
67 return observation[:2]
70def _measure_policy(actor, seed, goal=None):
72 observation, _ = env.reset(seed=seed)
75 action = actor.act(observation)
if goal
is None else actor.act(observation, goal)
76 observation, reward, terminated, truncated, _ = env.step(action)
79 if terminated
or truncated:
80 return total, steps, observation[:2]
84 return Grid(shape=(8, 8), features_domain=((-1., 1.), (-1., 1.)), fitness_domain=((0., HORIZON),))
87def _measure_goals(learner, path, held_out_seed):
88 learner.conditioned_policy().save(path)
89 actor = DescriptorConditionedPolicy.load(path)
91 for goal
in ((-0.5, -0.5), (-0.5, 0.5), (0.5, -0.5), (0.5, 0.5)):
92 reward, steps, achieved = _measure_policy(actor, held_out_seed, goal)
93 records.append(dict(target=goal, achieved=achieved.tolist(), steps=steps, return_=reward,
94 descriptor_error=float(np.linalg.norm(achieved - goal))))
98def _audit_archive(learner, seed):
100 changed_cells = audit_steps = 0
101 for elite
in learner.archive:
102 reward, steps, achieved = _measure_policy(learner.policy_for(elite), seed)
103 cell = learner.archive.index_grid(achieved)
104 changed_cells += cell != learner.archive.index_grid(elite.features)
105 rebinned[cell] = max(reward, rebinned.get(cell, 0.))
107 return dict(training_qd_score=learner.archive.qd_score(normalized=
False),
108 training_mean_elite_fitness=float(np.mean([elite.fitness.values[0]
for elite
in learner.archive])),
109 rebin_cells=len(rebinned), cell_changes=changed_cells,
110 rebin_collisions=len(learner.archive) - len(rebinned),
111 rebin_qd_score=sum(rebinned.values()), rebin_steps=audit_steps)
115def run(seed, steps, output_dir, selected=DEFAULT_METHODS, *, archive_audit=False, on_archive=None):
116 """Return one result per method and optionally observe evaluated QD learners."""
117 common = dict(policy=
PolicyConfig((16, 16)), seed=seed, max_episode_steps=HORIZON)
118 ppo =
PPOConfig(rollout_steps=64, batch_size=32, epochs=3, learning_rate=1e-3)
119 td3 =
TD3Config(replay_capacity=10_000, batch_size=32, learning_starts=128, critic_hidden_sizes=(32, 32))
120 conditioned = dict(td3=td3, critic_steps=32, length_scale=0.25)
122 (
"ppo", PPO, dict(config=ppo)),
123 (
"td3", TD3, dict(config=td3)),
124 (
"neural-map-elites", NeuralMAPElites, {}),
125 (
"ppo-assisted-map-elites", PPOAssistedMAPElites, dict(ppo=ppo)),
126 (
"pga-map-elites", PGAMAPElites, dict(td3=td3, critic_steps=32)),
127 (
"qd-pg", QDPG, dict(state_descriptor=state_descriptor, initial_policies=8,
128 gradient_steps_ratio=0.125, novelty_threshold=0.05, novelty_capacity=2048,
129 td3=replace(td3, actor_learning_rate=0.003, critic_learning_rate=0.003))),
130 (
"dcg-map-elites", DCGMAPElites, conditioned),
131 (
"dcrl-map-elites", DCRLMAPElites, conditioned),
132 (
"dcrl-no-injection", DCRLMAPElites, dict(conditioned, injections=0, pg_offspring=4)),
134 for name, method, options
in methods:
135 if name
not in selected:
137 search = issubclass(method, NeuralMAPElites)
139 options = dict(options, archive=_archive(), descriptor=descriptor)
140 if on_archive
is not None:
141 options[
"on_step"] =
lambda _, stats: on_archive(learner, stats)
142 learner = method(Tracking, **common, **options)
143 stats = learner.train(steps)
144 actor = learner.best_policy()
if search
else learner.policy
145 actor_path = output_dir / f
"{name}-{seed}.npz"
146 actor.save(actor_path)
147 restored = ContinuousPolicy.load(actor_path)
148 held_out_seed = seed + 100_000
149 held_out_return, replay_steps, _ = _measure_policy(restored, held_out_seed)
150 row = dict(method=name, seed=seed, steps=stats.env_steps, **asdict(stats),
151 occupied_cells=len(learner.archive)
if search
else None,
152 best_archive_fitness=learner.archive.best.fitness.values[0]
if search
else None,
153 held_out_seed=held_out_seed, held_out_return=held_out_return, replay_steps=replay_steps)
154 if name
in CONDITIONED_METHODS:
155 row[
"conditioned_goals"] = _measure_goals(
156 learner, output_dir / f
"{name}-{seed}-conditioned.npz", held_out_seed,
158 if search
and archive_audit:
159 row[
"archive_audit"] = _audit_archive(learner, held_out_seed)
164 parser = ArgumentParser(description=__doc__)
165 parser.add_argument(
"--steps", type=int, default=2048, help=
"Search steps per method and seed.")
166 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 29, 47])
167 parser.add_argument(
"--methods", nargs=
"+", choices=ALL_METHODS, default=DEFAULT_METHODS)
168 parser.add_argument(
"--archive-audit", action=
"store_true", help=
"Reevaluate and rebin every archived elite.")
169 parser.add_argument(
"--output-dir", type=Path, default=Path(
"build/continuous-qd-rl"))
170 args = parser.parse_args()
171 if args.steps < HORIZON:
172 parser.error(f
"--steps must be at least {HORIZON} to score a complete candidate.")
173 torch.set_num_threads(1)
174 args.output_dir.mkdir(parents=
True, exist_ok=
True)
175 with (args.output_dir /
"results.jsonl").open(
"w", encoding=
"utf-8")
as out:
176 for seed
in args.seeds:
177 for row
in run(seed, args.steps, args.output_dir, args.methods, archive_audit=args.archive_audit):
178 encoded = json.dumps(row, sort_keys=
True, allow_nan=
False)
179 print(encoded, flush=
True)
180 out.write(encoded +
"\n")
183if __name__ ==
"__main__":
A finite-horizon target-tracking environment with two bounded controls.
reset(self, *, seed=None, options=None)
Architecture of the actor and, for PPO, the separate value network.
Sampling and minibatch settings for the clipped PPO update.
Settings for the shared TD3 actor, critics, and replay buffer.