6"""Train and export policies for a small continuous velocity-control environment."""
8from argparse
import ArgumentParser
9from dataclasses
import asdict
10from itertools
import product
12from pathlib
import Path
13from time
import perf_counter
15import gymnasium
as gym
21 DCRLMAPElites, DescriptorConditionedPolicy, PolicyConfig, QDAC, QDACConfig, SAC, SACConfig,
22 SACPolicy, SkillConditionedPolicy, TD3Config, evaluate_skills,
27BOUNDS = ((-1., 1.), (-1., 1.))
28GOALS = tuple(product((-0.65, 0., 0.65), repeat=2))
29METHODS = (
"sac",
"qdac",
"dcrl-map-elites")
34 """Earn reward by matching a preferred velocity with two bounded controls.
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.
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))
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])
54 def _observation(self):
58 """Apply a physical action and truncate at the episode's time limit."""
60 raise ValueError(
"Invalid physical action.")
61 self.
_velocity = velocity_feature(
None, action,
None)
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.]
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)
79 return Grid(shape=(8, 8), features_domain=BOUNDS, fitness_domain=((0., HORIZON),))
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)
90 learner =
SAC(VelocityControl, config=
SACConfig(**settings, temperature_learning_rate=0.003), **common)
92 config =
QDACConfig(**settings, temperature_learning_rate=0.003, multiplier_hidden_sizes=(32, 32),
94 learner =
QDAC(VelocityControl, feature=velocity_feature, skill_bounds=BOUNDS, config=config, **common)
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"
103 learner.policy.save(path)
104 actor = SACPolicy.load(path)
106 def policy(obs, _skill):
107 return actor.act(obs)
110 learner.policy.save(path)
111 policy = SkillConditionedPolicy.load(path)
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,
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))
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")
142if __name__ ==
"__main__":
A small continuous velocity task with asymmetric physical action bounds.
reset(self, *, seed=None, options=None)
Add specialized conditioned actors to the MAP-Elites offspring batch.
Architecture of the actor and, for PPO, the separate value network.
Replay, entropy, and constraint settings for model-free QDAC.
Train a single goal-conditioned policy with model-free QDAC.
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Train a reusable standalone Soft Actor-Critic policy.
Settings for the shared TD3 actor, critics, and replay buffer.