5"""Train policies for a toy picking task with two equally valuable styles."""
10import gymnasium
as gym
14from qdpy.rl import PPOConfig, PolicyConfig, QSDPBT
19 """Eight picks share the same value on either side of the aisle."""
21 observation_space = gym.spaces.Box(0., 1., (1,), dtype=np.float32)
22 action_space = gym.spaces.Discrete(3)
24 def reset(self, *, seed=None, options=None):
25 super().reset(seed=seed)
27 return np.zeros(1, dtype=np.float32), {}
29 def step(self, action):
31 reward = 1.
if action
in (0, 1)
else .2
32 return np.array([self.
steps / 8.], dtype=np.float32), reward, self.
steps == 8,
False, {}
36 """Measure leftward preference and the fraction of consecutive side changes."""
37 actions = np.asarray(episode.actions)
38 bias = np.mean((actions == 0).astype(float) - (actions == 1))
39 changes = np.mean((actions[:-1] < 2) & (actions[1:] < 2) & (actions[1:] != actions[:-1]))
43def trial(seed, budget):
44 """Compare diversity training with the same PPO population trained for reward."""
45 for label, strength
in ((
"QSD-PBT", 5.), (
"Independent PPO", 0.)):
46 search =
QSDPBT(TwoStyles, descriptor=describe, descriptor_size=2, population_size=4,
47 max_episode_steps=8, ppo=
PPOConfig(rollout_steps=48, epochs=3,
48 batch_size=24, learning_rate=.003),
49 policy=
PolicyConfig((12,)), initial_weight=strength, decay_steps=700, seed=seed)
50 stats = search.train(budget)
51 audit = search.evaluate(episodes_per_policy=64, seed=510 + seed)
52 yield dict(method=label, seed=seed, steps=stats.training_steps, audit_steps=audit.steps,
53 mean_return=float(np.mean(audit.returns)), return_span=float(np.ptp(audit.returns)),
54 diversity_by_quality=audit.diversity_by_quality((0., 6., 7., 8.000001)),
55 diversity=audit.diversity_by_quality((0., 8.000001))[0],
56 returns=audit.returns, weights=stats.diversity_weights)
59if __name__ ==
"__main__":
60 parser = argparse.ArgumentParser(description=__doc__)
61 parser.add_argument(
"--budget", type=int, default=6144)
62 parser.add_argument(
"--seeds", nargs=
"+", type=int, default=[11, 22, 33])
63 args = parser.parse_args()
64 torch.set_num_threads(1)
65 for seed
in args.seeds:
66 for record
in trial(seed, args.budget):
67 print(json.dumps(record, sort_keys=
True, allow_nan=
False))
Architecture of the actor and, for PPO, the separate value network.
Sampling and minibatch settings for the clipped PPO update.
Discover policies with different behaviors at comparable quality levels.
Pick from either of two productive sides or skip the pick.