QDpy
Loading...
Searching...
No Matches
qdhuac.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Learn distinct trajectories in a small continuous position task."""
6
7import argparse
8import json
9from time import perf_counter
10
11import gymnasium as gym
12import numpy as np
13import torch
14
15from qdpy.rl import ContinuousPolicy, PolicyConfig, QDHUAC, SACConfig, TD3Config
16from qdpy.rl.rollout import _seed
17from qdpy.rl.td3 import _TD3Learner
18
19
20
21class CurveControl(gym.Env):
22 """Use a single continuous action to reach either side of a line."""
23
24 observation_space = gym.spaces.Box(-1., 1., shape=(2,), dtype=np.float32)
25 action_space = gym.spaces.Box(-1., 1., shape=(1,), dtype=np.float32)
26 horizon = 8
27
28 def reset(self, *, seed=None, options=None):
29 super().reset(seed=seed)
30 self.position = float(self.np_random.uniform(-.08, .08))
31 self.target = float(self.np_random.uniform(.45, .75))
32 self.step_count = 0
33 return self._observe(), {}
34
35 def _observe(self):
36 return np.array([self.position, self.target], dtype=np.float32)
37
38 def step(self, action):
39 self.position = float(np.clip(self.position + .26 * float(action[0]), -1., 1.))
40 reward = max(0., 1. - 1.5 * abs(abs(self.position) - self.target))
41 self.step_count += 1
42 return self._observe(), reward, self.step_count >= self.horizon, False, {}
43
44
46 """Use the same rollout budget, DNS selection, and emitter schedule for TD3."""
47
48 def _make_actor(self, env, config, device, seed):
49 return ContinuousPolicy(env.observation_space, env.action_space, config=config, device=device, seed=seed)
50
51 def _make_learner(self, actor, config, support, priority_exponent):
52 settings = TD3Config(batch_size=config.batch_size, learning_starts=config.learning_starts,
53 replay_capacity=config.replay_capacity, critic_hidden_sizes=config.critic_hidden_sizes,
54 actor_learning_rate=config.actor_learning_rate,
55 critic_learning_rate=config.critic_learning_rate, gamma=config.gamma)
56 return _TD3Learner(actor, settings, _seed(self._rng), self._counts)
57
58
59def _audit(trainer, seed):
60 env = CurveControl()
61 cells, returns, steps = {}, [], 0
62 for record in trainer.population:
63 actor = trainer.policy_for(record)
64 measurements, qualities = [], []
65 for index in range(3):
66 obs, _ = env.reset(seed=80_000 + 3 * seed + index)
67 coordinates, rewards = [], []
68 for _ in range(env.horizon):
69 obs, reward, _, _, _ = env.step(actor.act(obs))
70 coordinates.append(obs[0])
71 rewards.append(reward)
72 steps += 1
73 measurements.append(np.mean(coordinates))
74 qualities.append(sum(rewards))
75 point, quality = float(np.mean(measurements)), float(np.mean(qualities))
76 cell = min(9, int((point + 1.) * 5))
77 cells[cell] = max(quality, cells.get(cell, 0.))
78 returns.append(quality)
79 env.close()
80 return len(cells), sum(cells.values()), max(returns), steps
81
82
83
84def trial(seed, budget):
85 """Hold policy-generation sizes, reporting cells, and audit seeds fixed."""
86 for method, factory in (("qdhuac", QDHUAC), ("td3", _TD3Control)):
87 start = perf_counter()
88 trainer = factory(CurveControl, descriptor=lambda ep: (float(ep.observations[1:, 0].mean()),),
89 config=SACConfig(replay_capacity=2048, batch_size=24, learning_starts=48,
90 critic_hidden_sizes=(24, 24), actor_learning_rate=8e-4,
91 critic_learning_rate=1e-3),
92 policy=PolicyConfig((16,)), seed=seed, batch_size=6, population_size=12,
93 updates_per_transition=2, gradient_steps=3, atoms=21,
94 return_bounds=(0., 16.), max_episode_steps=CurveControl.horizon)
95 stats = trainer.train(budget)
96 training_s = perf_counter() - start
97 cells, score, best, audit_steps = _audit(trainer, seed)
98 yield dict(method=method, seed=seed, env_steps=stats.env_steps, audit_steps=audit_steps,
99 critic_updates=stats.critic_updates, optimizer_steps=stats.optimizer_steps,
100 cells=cells, qd_score=score, best_return=best, training_s=training_s,
101 elapsed_s=perf_counter() - start)
102
103
104def main():
105 """Run both learners on CPU and print their individual JSON records."""
106 parser = argparse.ArgumentParser(description=__doc__)
107 parser.add_argument("--steps", type=int, default=480)
108 parser.add_argument("--seeds", type=int, nargs="+", default=[7])
109 args = parser.parse_args()
110 if args.steps < 6 * CurveControl.horizon:
111 parser.error("--steps must cover at least six complete episodes")
112 torch.set_num_threads(1)
113 for seed in args.seeds:
114 for row in trial(seed, args.steps):
115 print(json.dumps(row))
116
117
118if __name__ == "__main__":
119 main()
A bounded control task with two rewarding directions.
Definition qdhuac.py:21
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Combine a categorical critic and several updates per transition with DNS.
Definition qdhuac.py:174
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Definition sac.py:23
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25