QDpy
Loading...
Searching...
No Matches
qsd_pbt.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Train policies for a toy picking task with two equally valuable styles."""
6
7import argparse
8import json
9
10import gymnasium as gym
11import numpy as np
12import torch
13
14from qdpy.rl import PPOConfig, PolicyConfig, QSDPBT
15
16
17
18class TwoStyles(gym.Env):
19 """Eight picks share the same value on either side of the aisle."""
20
21 observation_space = gym.spaces.Box(0., 1., (1,), dtype=np.float32)
22 action_space = gym.spaces.Discrete(3)
23
24 def reset(self, *, seed=None, options=None):
25 super().reset(seed=seed)
26 self.steps = 0
27 return np.zeros(1, dtype=np.float32), {}
28
29 def step(self, action):
30 self.steps += 1
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, {}
33
34
35def describe(episode):
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]))
40 return bias, changes
41
42
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)
57
58
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.
Definition policy.py:36
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
Discover policies with different behaviors at comparable quality levels.
Definition qsd_pbt.py:135
Pick from either of two productive sides or skip the pick.
Definition qsd_pbt.py:18