QDpy
Loading...
Searching...
No Matches
continuous_qd_rl.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3
5
6"""Run optional continuous QD+RL baselines on a small asymmetric Box task."""
7
8from argparse import ArgumentParser
9from dataclasses import asdict, replace
10import json
11from pathlib import Path
12
13import gymnasium as gym
14import numpy as np
15import torch
16
17from qdpy.containers import Grid
18from qdpy.rl import (
19 ContinuousPolicy, DCGMAPElites, DCRLMAPElites, DescriptorConditionedPolicy,
20 NeuralMAPElites, PGAMAPElites, PolicyConfig, PPO, PPOAssistedMAPElites, PPOConfig, QDPG, TD3, TD3Config,
21)
22
23
24HORIZON = 16
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)
28
29
30
31class Tracking(gym.Env):
32 """Reward tracking a target velocity and record the resulting displacement."""
33
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))
37
38 def _observation(self):
39 return np.array([*self.position, *self.target, self.steps / HORIZON], dtype=np.float32)
40
41 def reset(self, *, seed=None, options=None):
42 """Pick a seeded target and start at the origin."""
43 super().reset(seed=seed)
44 self.position = np.zeros(2)
45 self.target = self.np_random.uniform([0.2, -0.7], [0.8, -0.1])
46 self.steps = 0
47 return self._observation(), {}
48
49 def step(self, action):
50 """Apply a velocity command and score its squared tracking error."""
51 if not self.action_space.contains(action):
52 raise ValueError("Invalid physical action.")
53 velocity = (np.asarray(action, dtype=np.float64) - [1., 3.]) / [3., 2.]
54 self.position += velocity / HORIZON
55 reward = 1 - np.mean(np.square(velocity - self.target)) / 4
56 self.steps += 1
57 return self._observation(), float(reward), self.steps == HORIZON, False, {}
58
59
60
61def descriptor(episode):
62 return episode.observations[-1, :2]
63
64
65
66def state_descriptor(observation, info):
67 return observation[:2]
68
69
70def _measure_policy(actor, seed, goal=None):
71 with Tracking() as env:
72 observation, _ = env.reset(seed=seed)
73 total, steps = 0., 0
74 while True:
75 action = actor.act(observation) if goal is None else actor.act(observation, goal)
76 observation, reward, terminated, truncated, _ = env.step(action)
77 total += reward
78 steps += 1
79 if terminated or truncated:
80 return total, steps, observation[:2]
81
82
83def _archive():
84 return Grid(shape=(8, 8), features_domain=((-1., 1.), (-1., 1.)), fitness_domain=((0., HORIZON),))
85
86
87def _measure_goals(learner, path, held_out_seed):
88 learner.conditioned_policy().save(path)
89 actor = DescriptorConditionedPolicy.load(path)
90 records = []
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))))
95 return records
96
97
98def _audit_archive(learner, seed):
99 rebinned = {}
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.))
106 audit_steps += steps
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)
112
113
114
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)
121 methods = (
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)),
133 )
134 for name, method, options in methods:
135 if name not in selected:
136 continue
137 search = issubclass(method, NeuralMAPElites)
138 if search:
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,
157 )
158 if search and archive_audit:
159 row["archive_audit"] = _audit_archive(learner, held_out_seed)
160 yield row
161
162
163def main():
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")
181
182
183if __name__ == "__main__":
184 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.
Definition policy.py:36
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25