5"""Run PBT-MAP-Elites and BFM-QD with explicit real environment costs."""
8from dataclasses
import asdict
11import gymnasium
as gym
15from qdpy.rl import BFMQD, NeuralMAPElites, PBTMAPElites, PolicyConfig, SACConfig
19TARGET = np.array([.55, -.30], dtype=np.float32)
23 """A seeded two-axis control task with bounded actions and quadratic loss."""
27 self.
action_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
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(), {}
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, {}
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),))
45def descriptor(episode):
46 """Return the mean post-action position."""
47 return episode.observations[1:].mean(axis=0)
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)
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)
61 """Measure archived policies on common fresh starts and rebin the true scores."""
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)
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)))
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))
85def run(method, budget, seed):
86 """Search or train one variant, then report common held-out metrics."""
88 common = dict(descriptor=descriptor, max_episode_steps=HORIZON, seed=seed)
89 if method
in (
"pbt",
"pbt-no-injection"):
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)
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))
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.
Alternate independent SAC training, population replacement, and archive variation.
Architecture of the actor and, for PPO, the separate value network.
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.