5"""Train and export three categorical policies on a small navigation task."""
8from dataclasses
import asdict
10from pathlib
import Path
12import gymnasium
as gym
17from qdpy.rl import CategoricalPolicy, NeuralMAPElites, PPO, PPOAssistedMAPElites, PPOConfig, PolicyConfig
22 """Use two directions to move. Each of the four switches has a small cost."""
24 observation_space = gym.spaces.Box(low=0, high=1, shape=(3,), dtype=np.float32)
25 action_space = gym.spaces.MultiDiscrete([3, 3, 2, 2, 2, 2])
28 def _observation(self):
31 def reset(self, *, seed=None, options=None):
32 super().reset(seed=seed)
34 self.
position = self.np_random.uniform(0.4, 0.6, size=2)
37 def step(self, action):
39 raise ValueError(
"Invalid categorical action.")
40 direction = np.asarray(action[:2]) - 1
43 distance = np.linalg.norm(self.
position - (0.8, 0.7))
44 reward = 1. - distance / np.sqrt(2) - 0.005 * float(sum(action[2:]))
48def descriptor(episode):
49 """Use the final position as the two-dimensional archive descriptor."""
50 return episode.observations[-1, :2]
54 return Grid(shape=(8, 8), max_items_per_bin=1, fitness_domain=((0., 8.),),
55 features_domain=((0., 1.), (0., 1.)), fitness_weights=(1.,))
59def replay(path, seed):
60 """Run one held-out episode with deterministic actions."""
61 policy = CategoricalPolicy.load(path)
64 observation, _ = env.reset(seed=seed)
66 for step
in range(1, env.horizon + 1):
67 action = policy.act(observation, deterministic=
True)
68 observation, reward, terminated, truncated, _ = env.step(action)
70 if terminated
or truncated:
72 return {
"steps": step,
"return": total,
"descriptor": observation[:2].tolist()}
77def main(steps, seed, output_dir):
78 torch.set_num_threads(1)
79 output_dir.mkdir(parents=
True, exist_ok=
True)
81 ppo =
PPOConfig(rollout_steps=32, epochs=2, batch_size=16, learning_rate=0.003)
82 common = dict(policy=architecture, max_episode_steps=Navigation.horizon, seed=seed)
84 "ppo":
PPO(Navigation, config=ppo, **common),
85 "neural_map_elites":
NeuralMAPElites(Navigation, make_archive(), descriptor=descriptor,
86 initial_policies=4, **common),
88 Navigation, make_archive(), descriptor=descriptor, initial_policies=4,
89 ppo=ppo, ppo_probability=0.5, **common,
92 for method, search
in searches.items():
93 stats = search.train(steps)
94 actor = search.policy
if method ==
"ppo" else search.best_policy()
95 path = output_dir / f
"{method}.npz"
97 report = {
"method": method,
"seed": seed,
"env_steps": stats.env_steps, **asdict(stats),
98 "policy": path.name,
"heldout": replay(path, seed + 10000)}
100 report.update(occupied_cells=search.archive.filled_bins,
101 qd_score=search.archive.qd_score(normalized=
False),
102 best_fitness=search.archive.best_fitness.values[0])
103 print(json.dumps(report), flush=
True)
106if __name__ ==
"__main__":
107 parser = argparse.ArgumentParser(description=__doc__)
108 parser.add_argument(
"--steps", type=int, default=512, help=
"Environment-step budget for each method.")
109 parser.add_argument(
"--seed", type=int, default=42)
110 parser.add_argument(
"--output-dir", type=Path, default=Path(
"results.discrete-qd-rl"))
111 arguments = parser.parse_args()
112 if arguments.steps < Navigation.horizon:
113 parser.error(f
"--steps must be at least {Navigation.horizon} for an archived elite")
114 main(arguments.steps, arguments.seed, arguments.output_dir)
A bounded navigation task with six independent categorical controls.
Architecture of the actor and, for PPO, the separate value network.
Sampling and minibatch settings for the clipped PPO update.
Train PPO in a categorical or bounded continuous action space.
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Combine genetic variation with fresh PPO updates on copied elites.