5"""Learn distinct trajectories in a small continuous position task."""
9from time
import perf_counter
11import gymnasium
as gym
15from qdpy.rl import ContinuousPolicy, PolicyConfig, QDHUAC, SACConfig, TD3Config
22 """Use a single continuous action to reach either side of a line."""
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)
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))
38 def step(self, action):
39 self.
position = float(np.clip(self.
position + .26 * float(action[0]), -1., 1.))
46 """Use the same rollout budget, DNS selection, and emitter schedule for TD3."""
48 def _make_actor(self, env, config, device, seed):
49 return ContinuousPolicy(env.observation_space, env.action_space, config=config, device=device, seed=seed)
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)
59def _audit(trainer, seed):
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)
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)
80 return len(cells), sum(cells.values()), max(returns), steps
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)
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))
118if __name__ ==
"__main__":
A bounded control task with two rewarding directions.
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Architecture of the actor and, for PPO, the separate value network.
Combine a categorical critic and several updates per transition with DNS.
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Settings for the shared TD3 actor, critics, and replay buffer.