QDpy
Loading...
Searching...
No Matches
qdac.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3
5
6"""Train and export policies for a small continuous velocity-control environment."""
7
8from argparse import ArgumentParser
9from dataclasses import asdict
10from itertools import product
11import json
12from pathlib import Path
13from time import perf_counter
14
15import gymnasium as gym
16import numpy as np
17import torch
18
19from qdpy.containers import Grid
20from qdpy.rl import (
21 DCRLMAPElites, DescriptorConditionedPolicy, PolicyConfig, QDAC, QDACConfig, SAC, SACConfig,
22 SACPolicy, SkillConditionedPolicy, TD3Config, evaluate_skills,
23)
24
25
26HORIZON = 16
27BOUNDS = ((-1., 1.), (-1., 1.))
28GOALS = tuple(product((-0.65, 0., 0.65), repeat=2))
29METHODS = ("sac", "qdac", "dcrl-map-elites")
30
31
32
33class VelocityControl(gym.Env):
34 """Earn reward by matching a preferred velocity with two bounded controls.
35
36 Each observation contains the episode's preferred velocity, followed by
37 the current velocity. Each action sets the next velocity. The behavioral
38 descriptor is the mean commanded velocity, which equals the endpoint
39 displacement of an episode measured in units of one full horizon.
40 """
41
42 observation_space = gym.spaces.Box(-1., 1., (4,), dtype=np.float32)
43 action_space = gym.spaces.Box(np.array([-2., 1.], dtype=np.float32),
44 np.array([4., 5.], dtype=np.float32))
45
46 def reset(self, *, seed=None, options=None):
47 """Draw a preferred velocity and start from rest."""
48 super().reset(seed=seed)
49 self._preferred = self.np_random.uniform([0.25, -0.65], [0.65, -0.25])
50 self._velocity = np.zeros(2)
51 self._steps = 0
52 return self._observation(), {}
53
54 def _observation(self):
55 return np.concatenate((self._preferred, self._velocity)).astype(np.float32)
56
57 def step(self, action):
58 """Apply a physical action and truncate at the episode's time limit."""
59 if not self.action_space.contains(action):
60 raise ValueError("Invalid physical action.")
61 self._velocity = velocity_feature(None, action, None)
62 self._steps += 1
63 reward = 1 - np.square(self._velocity - self._preferred).mean() / 4
64 return self._observation(), float(reward), False, self._steps == HORIZON, {}
65
66
67
68def velocity_feature(observation, action, info):
69 """Return the two velocity coordinates commanded on this transition."""
70 return (np.asarray(action, dtype=np.float64) - [1., 3.]) / [3., 2.]
71
72
73def episode_descriptor(episode):
74 """Return the same mean velocity using DCRL's complete-episode API."""
75 return np.mean([velocity_feature(None, action, None) for action in episode.actions], axis=0)
76
77
78def _archive():
79 return Grid(shape=(8, 8), features_domain=BOUNDS, fitness_domain=((0., HORIZON),))
80
81
82
83def run(seed, steps, output_dir, selected=METHODS):
84 """Yield one reproducible measurement record per method."""
85 common = dict(policy=PolicyConfig((32, 32)), seed=seed, max_episode_steps=HORIZON)
86 settings = dict(replay_capacity=20_000, batch_size=64, learning_starts=128, critic_hidden_sizes=(64, 64),
87 actor_learning_rate=0.001, critic_learning_rate=0.001, gamma=0.85, tau=0.02)
88 for name in selected:
89 if name == "sac":
90 learner = SAC(VelocityControl, config=SACConfig(**settings, temperature_learning_rate=0.003), **common)
91 elif name == "qdac":
92 config = QDACConfig(**settings, temperature_learning_rate=0.003, multiplier_hidden_sizes=(32, 32),
93 delta=0.12)
94 learner = QDAC(VelocityControl, feature=velocity_feature, skill_bounds=BOUNDS, config=config, **common)
95 else:
96 learner = DCRLMAPElites(VelocityControl, archive=_archive(), descriptor=episode_descriptor,
97 td3=TD3Config(**settings), critic_steps=16, length_scale=0.25, **common)
98 start = perf_counter()
99 stats = learner.train(steps)
100 seconds = perf_counter() - start
101 path = output_dir / f"{name}-{seed}.npz"
102 if name == "sac":
103 learner.policy.save(path)
104 actor = SACPolicy.load(path)
105
106 def policy(obs, _skill):
107 return actor.act(obs)
108
109 elif name == "qdac":
110 learner.policy.save(path)
111 policy = SkillConditionedPolicy.load(path)
112 else:
113 learner.conditioned_policy().save(path)
114 policy = DescriptorConditionedPolicy.load(path)
115 held_out_seed = seed + 100_000
116 result = evaluate_skills(VelocityControl, policy, GOALS, feature=velocity_feature, skill_bounds=BOUNDS,
117 tolerance=0.25, episodes=3, max_episode_steps=HORIZON, seed=held_out_seed,
118 archive=_archive())
119 yield dict(method=name, seed=seed, held_out_seed=held_out_seed, train=asdict(stats),
120 train_steps=stats.env_steps, train_seconds=seconds, evaluation=asdict(result))
121
122
123def main():
124 parser = ArgumentParser(description=__doc__)
125 parser.add_argument("--steps", type=int, default=2048, help="Training interactions per method and seed.")
126 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 29, 47])
127 parser.add_argument("--methods", nargs="+", choices=METHODS, default=METHODS)
128 parser.add_argument("--output-dir", type=Path, default=Path("build/qdac-example"))
129 args = parser.parse_args()
130 if args.steps < HORIZON:
131 parser.error(f"--steps must be at least {HORIZON}.")
132 torch.set_num_threads(1)
133 args.output_dir.mkdir(parents=True, exist_ok=True)
134 with (args.output_dir / "results.jsonl").open("w", encoding="utf-8") as output:
135 for seed in args.seeds:
136 for row in run(seed, args.steps, args.output_dir, args.methods):
137 encoded = json.dumps(row, allow_nan=False, sort_keys=True)
138 print(encoded, flush=True)
139 output.write(encoded + "\n")
140
141
142if __name__ == "__main__":
143 main()
A small continuous velocity task with asymmetric physical action bounds.
Definition qdac.py:33
_observation(self)
Definition qdac.py:54
reset(self, *, seed=None, options=None)
Definition qdac.py:46
step(self, action)
Definition qdac.py:57
Add specialized conditioned actors to the MAP-Elites offspring batch.
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Replay, entropy, and constraint settings for model-free QDAC.
Definition qdac.py:25
Train a single goal-conditioned policy with model-free QDAC.
Definition qdac.py:261
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Definition sac.py:23
Train a reusable standalone Soft Actor-Critic policy.
Definition sac.py:250
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25