5"""Train and export optional continuous QDAC policies on CPU."""
8from dataclasses
import asdict
10from pathlib
import Path
11from time
import perf_counter
13import gymnasium
as gym
19 PolicyConfig, QDAC, QDACConfig, QDACMB, QDACMBConfig, QDACMBPolicy, QDACMBWorldConfig,
20 SMERL, SMERLConfig, SMERLPolicy, SkillConditionedPolicy, evaluate_discovered_skills, evaluate_skills,
25_GOALS = tuple((goal,)
for goal
in np.linspace(-.8, .8, 9))
30 """A discrete-time damped velocity, measured before the next observation."""
32 observation_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
33 action_space = gym.spaces.Box(2., 6., (1,), dtype=np.float32)
38 def reset(self, *, seed=None, options=None):
39 """Draw a preferred velocity and start near rest."""
40 super().
reset(seed=seed)
41 self.
velocity = self.np_random.uniform(-.15, .15)
42 self.
target = self.np_random.uniform(.20, .50)
44 return self.
_obs(), {}
47 """Update velocity with the selected physical action."""
49 raise ValueError(
"Expected a bounded physical action.")
50 self.
velocity, = velocity_feature(self.
_obs(), action, {})
53 return self.
_obs(), reward,
False, self.
steps == _HORIZON, {}
57def velocity_feature(observation, action, info):
58 """Return the commanded velocity after applying damping."""
59 return (.40 * float(observation[0]) + .30 * (float(action[0]) - 4.),)
63def trials(steps, seed, output_dir, *, timing=False, selected=(
"qdac",
"qdac-mb"), smerl_threshold=14.):
64 """Use the same reset seeds, descriptors, and achieved-cell audit geometry."""
65 settings = dict(replay_capacity=20_000, learning_starts=64, gamma=.90, tau=.02,
66 actor_learning_rate=.001, critic_learning_rate=.001, critic_hidden_sizes=(32, 32))
67 qdac_settings = settings | dict(delta=.15, multiplier_learning_rate=.001, lambda_scale=4.)
68 common = dict(max_episode_steps=_HORIZON, policy=
PolicyConfig((32, 32)), seed=seed)
69 skills = dict(feature=velocity_feature, skill_bounds=_BOUNDS)
71 def achieved(episode):
72 measured = [velocity_feature(obs, action, {})
73 for obs, action
in zip(episode.observations[:-1], episode.actions, strict=
True)]
74 return np.mean(measured, axis=0)
76 for method
in selected:
78 config =
QDACConfig(batch_size=32, initial_temperature=.2, temperature_learning_rate=.001,
79 multiplier_hidden_sizes=(32, 32), **qdac_settings)
80 search, loader =
QDAC(VelocityTrack, config=config, **common, **skills), SkillConditionedPolicy
81 elif method ==
"qdac-mb":
82 config =
QDACMBConfig(world=QDACMBWorldConfig(32, 4, 4, 48), batch_size=8, sequence_length=8,
83 world_learning_rate=.001, imagination_batch_size=24,
84 imagination_horizon=9, train_every=4, free_nats=.2, **qdac_settings)
85 search, loader =
QDACMB(VelocityTrack, config=config, **common, **skills), QDACMBPolicy
87 config =
SMERLConfig(skills=len(_GOALS), batch_size=32, initial_temperature=.2,
88 temperature_learning_rate=.001, diversity_weight=1.,
89 discriminator_hidden_sizes=(32, 32), discriminator_learning_rate=.001, **settings)
90 search =
SMERL(VelocityTrack, return_threshold=smerl_threshold, config=config, **common)
92 start = perf_counter()
93 stats = search.train(steps)
94 elapsed = perf_counter() - start
95 path = output_dir / f
"{method}-{seed}.npz"
96 search.policy.save(path)
97 actor = loader.load(path)
98 archive =
Grid(shape=9, features_domain=_BOUNDS, fitness_domain=((0., _HORIZON),))
99 audit_options = dict(episodes=3, max_episode_steps=_HORIZON, seed=10_000 + seed, archive=archive)
100 if method ==
"smerl":
101 audit = evaluate_discovered_skills(VelocityTrack, actor, descriptor=achieved, **audit_options)
103 audit = evaluate_skills(VelocityTrack, actor, _GOALS, feature=velocity_feature, tolerance=.23,
105 result = dict(method=method, task=
"velocity-track", seed=seed, real_steps=stats.env_steps,
106 actor_updates=stats.actor_updates, imagined_steps=getattr(stats,
"imagined_steps", 0),
107 world_model_updates=getattr(stats,
"world_model_updates", 0),
108 replay_transitions=getattr(stats,
"replay_transitions",
None), audit=asdict(audit))
109 if method ==
"smerl":
110 result.update(return_threshold=smerl_threshold, completed_episodes=stats.completed_episodes,
111 eligible_episodes=stats.eligible_episodes)
113 result[
"train_seconds"] = elapsed
118 parser = argparse.ArgumentParser(description=__doc__)
119 parser.add_argument(
"--steps", type=int, default=2048)
120 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 23, 47])
121 parser.add_argument(
"--methods", nargs=
"+", choices=[
"qdac",
"qdac-mb",
"smerl"], default=[
"qdac",
"qdac-mb"])
122 parser.add_argument(
"--smerl-threshold", type=float, default=14.)
123 parser.add_argument(
"--timing", action=
"store_true")
124 parser.add_argument(
"--output-dir", type=Path, default=Path(
"build/qdac-mb-example"))
125 args = parser.parse_args()
127 parser.error(
"--steps must be positive.")
128 torch.set_num_threads(1)
129 args.output_dir.mkdir(parents=
True, exist_ok=
True)
130 with (args.output_dir /
"results.jsonl").open(
"w", encoding=
"utf-8")
as output:
131 for seed
in args.seeds:
132 for result
in trials(args.steps, seed, args.output_dir, timing=args.timing,
133 selected=args.methods, smerl_threshold=args.smerl_threshold):
134 line = json.dumps(result, allow_nan=
False, sort_keys=
True)
136 output.write(line +
"\n")
139if __name__ ==
"__main__":
Track a preferred velocity under bounded, asymmetric physical controls.
reset(self, *, seed=None, options=None)
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.
Specify work budgets and optimization settings for QDAC-MB.
Train a recurrent skill-conditioned policy with real replay and imagined trajectories.
Configure SAC and the categorical skill discriminator.
Learn discrete latent skills with episode-return gating.