QDpy
Loading...
Searching...
No Matches
discrete_qd_rl.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Train and export three categorical policies on a small navigation task."""
6
7import argparse
8from dataclasses import asdict
9import json
10from pathlib import Path
11
12import gymnasium as gym
13import numpy as np
14import torch
15
16from qdpy.containers import Grid
17from qdpy.rl import CategoricalPolicy, NeuralMAPElites, PPO, PPOAssistedMAPElites, PPOConfig, PolicyConfig
18
19
20
21class Navigation(gym.Env):
22 """Use two directions to move. Each of the four switches has a small cost."""
23
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])
26 horizon = 8
27
28 def _observation(self):
29 return np.array([*self.position, 1. - self.turn / self.horizon], dtype=np.float32)
30
31 def reset(self, *, seed=None, options=None):
32 super().reset(seed=seed)
33 self.turn = 0
34 self.position = self.np_random.uniform(0.4, 0.6, size=2)
35 return self._observation(), {}
36
37 def step(self, action):
38 if not self.action_space.contains(action):
39 raise ValueError("Invalid categorical action.")
40 direction = np.asarray(action[:2]) - 1
41 self.position = np.clip(self.position + direction * 0.10, 0, 1)
42 self.turn += 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:]))
45 return self._observation(), float(reward), self.turn == self.horizon, False, {}
46
47
48def descriptor(episode):
49 """Use the final position as the two-dimensional archive descriptor."""
50 return episode.observations[-1, :2]
51
52
53def make_archive():
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.,))
56
57
58
59def replay(path, seed):
60 """Run one held-out episode with deterministic actions."""
61 policy = CategoricalPolicy.load(path)
62 env = Navigation()
63 try:
64 observation, _ = env.reset(seed=seed)
65 total = 0.0
66 for step in range(1, env.horizon + 1):
67 action = policy.act(observation, deterministic=True)
68 observation, reward, terminated, truncated, _ = env.step(action)
69 total += reward
70 if terminated or truncated:
71 break
72 return {"steps": step, "return": total, "descriptor": observation[:2].tolist()}
73 finally:
74 env.close()
75
76
77def main(steps, seed, output_dir):
78 torch.set_num_threads(1)
79 output_dir.mkdir(parents=True, exist_ok=True)
80 architecture = PolicyConfig(hidden_sizes=(32, 32))
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)
83 searches = {
84 "ppo": PPO(Navigation, config=ppo, **common),
85 "neural_map_elites": NeuralMAPElites(Navigation, make_archive(), descriptor=descriptor,
86 initial_policies=4, **common),
87 "ppo_assisted_map_elites": PPOAssistedMAPElites(
88 Navigation, make_archive(), descriptor=descriptor, initial_policies=4,
89 ppo=ppo, ppo_probability=0.5, **common,
90 ),
91 }
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"
96 actor.save(path)
97 report = {"method": method, "seed": seed, "env_steps": stats.env_steps, **asdict(stats),
98 "policy": path.name, "heldout": replay(path, seed + 10000)}
99 if method != "ppo":
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)
104
105
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.
Definition policy.py:36
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
Train PPO in a categorical or bounded continuous action space.
Definition ppo.py:166
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Definition search.py:24
Combine genetic variation with fresh PPO updates on copied elites.
Definition search.py:241