QDpy
Loading...
Searching...
No Matches
dqs.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Explore a continuous line with two rewarding targets and fixed-step episodes."""
6
7import argparse
8import json
9from time import perf_counter
10
11import gymnasium as gym
12import numpy as np
13import torch
14
15from qdpy.containers import Grid
16from qdpy.rl import DOMiNO, DiverseQualitySpecies, PPOConfig, PolicyConfig, TD3Config
17
18
19
20class TwoPeaks(gym.Env):
21 """Use one signed action to move along a line and measure the center of each trajectory."""
22
23 observation_space = gym.spaces.Box(-1., 1., shape=(2,), dtype=np.float32)
24 action_space = gym.spaces.Box(-1., 1., shape=(1,), dtype=np.float32)
25 horizon = 12
26
27 def reset(self, *, seed=None, options=None):
28 super().reset(seed=seed)
29 self.position = float(self.np_random.uniform(-.08, .08))
30 self.target = float(self.np_random.uniform(.62, .78))
31 self.tick = 0
32 return self._observe(), {}
33
34 def _observe(self):
35 return np.array([self.position, self.target], dtype=np.float32)
36
37 def step(self, action):
38 self.position = float(np.clip(self.position + .21 * float(action[0]), -1., 1.))
39 reward = max(0., 1. - 1.45 * abs(abs(self.position) - self.target))
40 self.tick += 1
41 return self._observe(), reward, self.tick == self.horizon, False, {}
42
43
44def _grid():
45 return Grid(shape=(9,), features_domain=((-1., 1.),),
46 fitness_domain=((0., float(TwoPeaks.horizon)),), fitness_weights=(1.,))
47
48
49
50def trial(seed, budget):
51 """Report coverage of achieved bins and rewarding directions using an independent reset panel."""
52 horizon = TwoPeaks.horizon
53 config = PolicyConfig((24, 24))
54 for method in ("dqs", "dqs_no_bonus", "domino"):
55 start = perf_counter()
56 discriminator_updates = offspring = 0
57 geometry = _grid()
58 if method == "domino":
59 trainer = DOMiNO(TwoPeaks, feature=lambda observation, action, info: (observation[0],),
60 feature_dimension=1, num_skills=4, policy=config,
61 reward_floor=.55, config=PPOConfig(rollout_steps=24, epochs=3,
62 batch_size=12, learning_rate=2e-3),
63 max_episode_steps=horizon, seed=seed)
64 stats = trainer.train(budget)
65 audit = trainer.evaluate(episodes_per_skill=5, seed=80_000 + seed)
66 panel = [(row.occupancy, row.return_mean) for row in audit.skills]
67 audit_steps = audit.steps
68 else:
69 trainer = DiverseQualitySpecies(TwoPeaks, num_species=4, species_size=3, elites=1, policy=config,
70 td3=TD3Config(replay_capacity=4096, critic_hidden_sizes=(32, 32),
71 batch_size=32, learning_starts=96,
72 actor_learning_rate=2e-3),
73 update_frequency=3, gradient_steps=16, max_episode_steps=horizon,
74 diversity_scale=.25 if method == "dqs" else 0., seed=seed)
75 stats = trainer.train(budget)
76 # Score the best measured member of each species to match the four DOMiNO policies.
77 audit = trainer.evaluate(episodes=5, seed=80_000 + seed,
78 descriptor=lambda episode: (float(episode.observations[:-1, 0].mean()),),
79 archive=geometry, best_per_species=True)
80 panel = [(row.descriptor, row.return_) for row in audit.policies]
81 audit_steps = audit.env_steps
82 discriminator_updates, offspring = stats.discriminator_updates, stats.pg_offspring
83
84 best_by_cell, directions = {}, set()
85 for behavior, score in panel:
86 cell = geometry.index_grid(behavior)
87 best_by_cell[cell] = max(best_by_cell.get(cell, 0.), score)
88 if score / horizon >= .55 and abs(behavior[0]) >= .2:
89 directions.add(int(np.sign(behavior[0])))
90 yield dict(method=method, seed=seed, env_steps=stats.env_steps, audit_steps=audit_steps,
91 occupied=len(best_by_cell), score=sum(best_by_cell.values()), high_return_directions=len(directions),
92 mean_return=float(np.mean([score for _, score in panel])), updates=stats.optimizer_steps,
93 discriminator_updates=discriminator_updates, refined=offspring,
94 elapsed_s=perf_counter() - start)
95
96
97def main():
98 """Run seeded CPU comparisons and print JSON records."""
99 parser = argparse.ArgumentParser(description=__doc__)
100 parser.add_argument("--seeds", type=int, nargs="+", default=[7])
101 parser.add_argument("--steps", type=int, default=1440)
102 args = parser.parse_args()
103 if args.steps < 4 * 3 * TwoPeaks.horizon:
104 parser.error("--steps must be at least one full DQS generation (144 steps)")
105 torch.set_num_threads(1)
106 for seed in args.seeds:
107 for record in trial(seed, args.steps):
108 print(json.dumps(record))
109
110
111if __name__ == "__main__":
112 main()
Continuous controls can move toward either of two rewarding positions.
Definition dqs.py:20
int horizon
Definition dqs.py:25
int tick
Definition dqs.py:31
_observe(self)
Definition dqs.py:34
Train a shared actor for distinct policies subject to a task reward floor.
Definition domino.py:75
Evolve multiple high-performing species without requiring a descriptor grid.
Definition dqs.py:97
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
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25