5"""Search a two-axis control repertoire and independently verify its real returns."""
9from dataclasses
import asdict
10from time
import perf_counter
12import gymnasium
as gym
16from qdpy.rl import DynamicsAwareQD, GAILEBC, NeuralMAPElites, PPGA, PPOConfig, PolicyConfig
20_TARGET = np.array([.55, -.35], dtype=np.float32)
23def reward(observation, action, successor):
24 """Score the successor by its squared distance to the target."""
25 return 1. - .15 * float(np.square(successor - _TARGET).sum())
29 """Move a two-dimensional state with bounded controls and seeded resets."""
31 def __init__(self, *, reveal_reward=True):
33 self.
action_space = gym.spaces.Box(-1., 1., shape=(2,), dtype=np.float32)
36 def reset(self, *, seed=None, options=None):
37 super().reset(seed=seed)
38 self.
state = self.np_random.uniform(-.15, .15, size=2).astype(np.float32)
39 return self.
state.copy(), {}
41 def step(self, action):
42 successor = np.clip(.72 * self.
state + .28 * action, -1., 1.).astype(np.float32)
44 self.
state = successor
45 return successor.copy(), score,
False,
False, {}
48def measure(observation, action, successor, info):
49 """Use the mean position as the archive descriptor."""
53def descriptor(episode):
54 """Measure mean position from a completed trajectory."""
55 return episode.observations[1:].mean(axis=0)
58def demonstrations(*, with_measures=False):
59 """Generate four demonstrations, optionally including each step's measures."""
61 observations, actions, measures = [], [], []
62 for seed, offset
in enumerate(((0., 0.), (-.35, 0.), (0., .4), (.2, -.15))):
63 obs, _ = env.reset(seed=seed)
64 for _
in range(_HORIZON):
65 action = np.clip(1.25 * (_TARGET + offset) - .25 * obs, -1., 1.).astype(np.float32)
66 observations.append(obs)
67 actions.append(action)
68 successor, _, _, _, info = env.step(action)
70 measures.append(measure(obs, action, successor, info))
73 rows = np.stack(observations), np.stack(actions)
74 return (*rows, np.stack(measures))
if with_measures
else rows
80 for individual
in search.archive:
81 actor = search.policy_for(individual)
82 returns, measures = [], []
83 for seed
in (1003, 1007):
84 obs, _ = env.reset(seed=seed)
85 successors, rewards = [], []
86 for _
in range(_HORIZON):
87 obs, fitness, *_ = env.step(actor.act(obs))
88 successors.append(obs)
89 rewards.append(fitness)
90 returns.append(sum(rewards))
91 measures.append(np.mean(successors, axis=0))
92 cell = search.archive.index_grid(tuple(np.mean(measures, axis=0)))
93 scores[cell] = max(scores.get(cell, -np.inf), float(np.mean(returns)))
95 return dict(verified_cells=len(scores), verified_qd=sum(scores.values()),
96 verified_best=max(scores.values(), default=
None),
97 verification_steps=2 * _HORIZON * len(search.archive))
100def run(method, budget, seed):
101 """Report training costs and held-out true-return metrics for one run."""
102 archive =
Grid(shape=(10, 10), max_items_per_bin=1,
103 fitness_domain=((-np.inf, np.inf),), features_domain=((-1., 1.), (-1., 1.)))
104 common = dict(policy=
PolicyConfig((12,)), max_episode_steps=_HORIZON, seed=seed)
105 if method
in (
"ppga",
"gail",
"gail-ebc"):
106 options = dict(measure=measure, ppo=
PPOConfig(rollout_steps=24, epochs=2, batch_size=24),
107 population_size=7, sigma0=.7, learning_rate=.2, **common)
109 search =
PPGA(TargetControl, archive, **options)
111 search =
GAILEBC(
lambda:
TargetControl(reveal_reward=
False), archive, demonstrations=demonstrations(),
112 curiosity_weight=0.
if method ==
"gail" else .5,
113 discriminator=
PolicyConfig((16,)), discriminator_updates=4,
114 discriminator_batch_size=32, **options)
116 common.update(initial_policies=6, iso_sigma=.1, line_sigma=.3)
117 if method ==
"da-qd":
118 search =
DynamicsAwareQD(TargetControl, archive, descriptor=descriptor, model_reward=reward,
119 min_model_steps=72, model_policy=
PolicyConfig((24, 24)),
120 model_updates=12, model_batch_size=48, imagined_candidates=24,
121 max_transfers=4, **common)
123 search =
NeuralMAPElites(TargetControl, archive, descriptor=descriptor, **common)
124 start = perf_counter()
125 stats = search.train(budget)
126 seconds = perf_counter() - start
127 result = dict(method=method, seed=seed, budget=budget, env_steps=stats.env_steps, seconds=seconds,
128 occupied_cells=len(archive), **asdict(stats), **_audit(search))
129 if method
in (
"gail",
"gail-ebc"):
130 result[
"demonstration_steps"] = 4 * _HORIZON
134if __name__ ==
"__main__":
135 parser = argparse.ArgumentParser(description=__doc__)
136 parser.add_argument(
"methods", nargs=
"+", choices=(
"ppga",
"gail",
"gail-ebc",
"da-qd",
"neural-me"))
137 parser.add_argument(
"--budget", type=int, default=1152)
138 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 22, 33])
139 args = parser.parse_args()
140 for method
in args.methods:
141 for seed
in args.seeds:
142 print(json.dumps(run(method, args.budget, seed), sort_keys=
True))
Discover policies with an imagined repertoire and verify them in the environment.
Recover a reward from demonstrations and add an archive-occupancy PPO bonus.
Architecture of the actor and, for PPO, the separate value network.
Branch from PPO objective and descriptor directions and walk with xNES.
Sampling and minibatch settings for the clipped PPO update.
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.