QDpy
Loading...
Searching...
No Matches
brpg_map_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5import argparse
6import json
7from time import perf_counter
8
9import gymnasium as gym
10import numpy as np
11import torch
12
13from qdpy.containers import Grid
14from qdpy.rl import BRPGMAPElites, DCRLMAPElites, PolicyConfig, TD3Config
15
16
17class TrackingTask(gym.Env):
18 """Track alternating controls while reaching different mean action values."""
19
20 observation_space = gym.spaces.Box(-1, 1, (1,), dtype=np.float32)
21 action_space = gym.spaces.Box(-1, 1, (2,), dtype=np.float32)
22
23 def reset(self, *, seed=None, options=None):
24 super().reset(seed=seed)
25 self.elapsed = 0
26 self.sign = int(self.np_random.choice([-1, 1]))
27 return self.observation(), {}
28
29 def observation(self):
30 return np.array([self.sign], np.float32)
31
32 def step(self, action):
33 reward = 1 - .2 * ((action[0] - .7) ** 2 + (action[1] - .55 * self.sign) ** 2)
34 # Keep a nonnegative task reward for the DCRL baseline.
35 reward = max(0., float(reward))
36 self.elapsed += 1
37 self.sign *= -1
38 return self.observation(), reward, False, self.elapsed == 8, {"feature": (float(action[0]),)}
39
40
41def assess(policy, seed):
42 """Measure conditioned actor return and tracking error over 10 held-out episodes."""
43 env = TrackingTask()
44 errors, returns = [], []
45 for goal in np.linspace(-.8, .8, 5):
46 for offset in (1000, 2000):
47 obs, _ = env.reset(seed=seed + offset)
48 actions, rewards = [], []
49 for _ in range(8):
50 action = policy.act(obs, [goal])
51 obs, reward, _, _, _ = env.step(action)
52 actions.append(action[0])
53 rewards.append(reward)
54 errors.append(abs(np.mean(actions) - goal))
55 returns.append(sum(rewards))
56 env.close()
57 return float(np.mean(errors)), float(np.mean(returns))
58
59
60def benchmark(seed, steps):
61 """Hold the archive, policy layout, and training interactions fixed."""
62 for method in ("brpg", "dcrl"):
63 grid = Grid(shape=12, fitness_domain=((0, 8),), features_domain=((-1, 1),))
64 options = dict(td3=TD3Config(batch_size=64, learning_starts=128, replay_capacity=8192,
65 actor_learning_rate=.001, critic_learning_rate=.001,
66 critic_hidden_sizes=(32, 32), policy_delay=4, tau=.02),
67 policy=PolicyConfig((16, 16)), initial_policies=16, max_episode_steps=8,
68 genetic_offspring=4, pg_offspring=2, injections=2, critic_steps=4,
69 pg_steps=2, iso_sigma=.06, line_sigma=.3, seed=seed)
70 if method == "brpg":
71 search = BRPGMAPElites(TrackingTask, grid, feature=lambda obs, action, next_obs, info: info["feature"],
72 behavior_gamma=.8, **options)
73 else:
74 search = DCRLMAPElites(TrackingTask, grid, descriptor=lambda ep: (np.asarray(ep.actions)[:, 0].mean(),),
75 **options)
76 start = perf_counter()
77 stats = search.train(steps)
78 elapsed = perf_counter() - start
79 error, mean_return = assess(search.conditioned_policy(), seed)
80 yield dict(seed=seed, method=method, steps=stats.env_steps, optimizer_steps=stats.optimizer_steps,
81 coverage=grid.filled_bins / 12, qd_score=sum(ind.fitness.values[0] for ind in grid),
82 descriptor_mae=error, conditioned_return=mean_return, assessment_steps=80, seconds=elapsed)
83
84
85if __name__ == "__main__":
86 parser = argparse.ArgumentParser(description=__doc__)
87 parser.add_argument("--steps", type=int, default=6400)
88 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33])
89 args = parser.parse_args()
90 torch.set_num_threads(1)
91 for seed in args.seeds:
92 for result in benchmark(seed, args.steps):
93 print(json.dumps(result, sort_keys=True))
Evolve continuous actors using separate reward and behavior gradients.
Definition brpg.py:173
Add specialized conditioned actors to the MAP-Elites offspring batch.
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25