QDpy
Loading...
Searching...
No Matches
targeted_policy_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run PBT-MAP-Elites and BFM-QD with explicit real environment costs."""
6
7import argparse
8from dataclasses import asdict
9import json
10
11import gymnasium as gym
12import numpy as np
13
14from qdpy.containers import Grid
15from qdpy.rl import BFMQD, NeuralMAPElites, PBTMAPElites, PolicyConfig, SACConfig
16
17
18HORIZON = 12
19TARGET = np.array([.55, -.30], dtype=np.float32)
20
21
22class PositionControl(gym.Env):
23 """A seeded two-axis control task with bounded actions and quadratic loss."""
24
25 def __init__(self):
26 self.observation_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
27 self.action_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
28
29 def reset(self, *, seed=None, options=None):
30 super().reset(seed=seed)
31 self.state = self.np_random.uniform(-.12, .12, 2).astype(np.float32)
32 return self.state.copy(), {}
33
34 def step(self, action):
35 self.state = (.65 * self.state + .35 * action).astype(np.float32)
36 reward = 1. - .15 * float(np.sum((self.state - TARGET) ** 2))
37 return self.state.copy(), reward, False, False, {}
38
39
40def archive():
41 """Create a common archive for the mean achieved position."""
42 return Grid(shape=(10, 10), features_domain=((-1., 1.), (-1., 1.)), fitness_domain=((0., 12.1),))
43
44
45def descriptor(episode):
46 """Return the mean post-action position."""
47 return episode.observations[1:].mean(axis=0)
48
49
50def frozen_controller(observation, latent_code):
51 """Use a known latent-to-action map as a stand-in for a pretrained controller."""
52 return np.clip(.76 * latent_code[:2] - .25 * observation, -1., 1.).astype(np.float32)
53
54
55def backward_features(observation):
56 """Use a fixed basis containing the components of the task reward."""
57 return np.array([observation[0], observation[1], 1. - np.sum(observation ** 2)], dtype=float)
58
59
60def audit(search):
61 """Measure archived policies on common fresh starts and rebin the true scores."""
62 env = PositionControl()
63 scores = {}
64 try:
65 for elite in search.archive:
66 actor = search.policy_for(elite)
67 total, measures = [], []
68 for seed in (1003, 1007):
69 obs, _ = env.reset(seed=seed)
70 rewards, states = [], []
71 for _ in range(HORIZON):
72 obs, reward, *_ = env.step(actor.act(obs))
73 rewards.append(reward)
74 states.append(obs)
75 total.append(sum(rewards))
76 measures.append(np.mean(states, axis=0))
77 cell = search.archive.index_grid(tuple(np.mean(measures, axis=0)))
78 scores[cell] = max(scores.get(cell, 0.), float(np.mean(total)))
79 finally:
80 env.close()
81 return dict(verified_cells=len(scores), verified_qd=sum(scores.values()),
82 verified_best=max(scores.values(), default=None), audit_steps=2 * HORIZON * len(search.archive))
83
84
85def run(method, budget, seed):
86 """Search or train one variant, then report common held-out metrics."""
87 grid = archive()
88 common = dict(descriptor=descriptor, max_episode_steps=HORIZON, seed=seed)
89 if method in ("pbt", "pbt-no-injection"):
90 search = PBTMAPElites(PositionControl, grid, policy=PolicyConfig((12,)), population_size=4,
91 exploit_count=1, archive_replacements=1 if method == "pbt" else 0,
92 training_steps_per_agent=24, offspring=2, iso_sigma=.06,
93 sac=SACConfig(replay_capacity=512, learning_starts=8, batch_size=16,
94 critic_hidden_sizes=(16, 16)), **common)
95 elif method in ("bfm", "bfm-bi"):
96 search = BFMQD(PositionControl, grid, controller=frozen_controller, latent_size=3,
97 backward_features=backward_features if method == "bfm-bi" else None,
98 backward_step=.15, iso_sigma=.5, initial_policies=6, **common)
99 else:
100 search = NeuralMAPElites(PositionControl, grid, policy=PolicyConfig((12,)), iso_sigma=.06,
101 initial_policies=6, **common)
102 stats = search.train(budget)
103 return dict(method=method, seed=seed, budget=budget, env_steps=stats.env_steps,
104 occupied_cells=len(grid), **asdict(stats), **audit(search))
105
106
107if __name__ == "__main__":
108 parser = argparse.ArgumentParser(description=__doc__)
109 parser.add_argument("methods", nargs="+", choices=("pbt", "pbt-no-injection", "bfm", "bfm-bi", "neural-me"))
110 parser.add_argument("--budget", type=int, default=1248)
111 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33])
112 args = parser.parse_args()
113 for method in args.methods:
114 for seed in args.seeds:
115 print(json.dumps(run(method, args.budget, seed), sort_keys=True, allow_nan=False))
Run MAP-Elites over a pretrained controller's latent sphere.
Definition bfm_qd.py:75
Alternate independent SAC training, population replacement, and archive variation.
Definition pbt.py:80
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Definition sac.py:23
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Definition search.py:24