7from time
import perf_counter
14from qdpy.rl import BRPGMAPElites, DCRLMAPElites, PolicyConfig, TD3Config
18 """Track alternating controls while reaching different mean action values."""
20 observation_space = gym.spaces.Box(-1, 1, (1,), dtype=np.float32)
21 action_space = gym.spaces.Box(-1, 1, (2,), dtype=np.float32)
23 def reset(self, *, seed=None, options=None):
24 super().reset(seed=seed)
26 self.
sign = int(self.np_random.choice([-1, 1]))
29 def observation(self):
30 return np.array([self.
sign], np.float32)
32 def step(self, action):
33 reward = 1 - .2 * ((action[0] - .7) ** 2 + (action[1] - .55 * self.
sign) ** 2)
35 reward = max(0., float(reward))
38 return self.
observation(), reward,
False, self.
elapsed == 8, {
"feature": (float(action[0]),)}
41def assess(policy, seed):
42 """Measure conditioned actor return and tracking error over 10 held-out episodes."""
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 = [], []
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))
57 return float(np.mean(errors)), float(np.mean(returns))
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)
71 search =
BRPGMAPElites(TrackingTask, grid, feature=
lambda obs, action, next_obs, info: info[
"feature"],
72 behavior_gamma=.8, **options)
74 search =
DCRLMAPElites(TrackingTask, grid, descriptor=
lambda ep: (np.asarray(ep.actions)[:, 0].mean(),),
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)
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.
Add specialized conditioned actors to the MAP-Elites offspring batch.
Architecture of the actor and, for PPO, the separate value network.
Settings for the shared TD3 actor, critics, and replay buffer.