Configuring an RL Agent#
In the previous tutorial, we saw how to train an RL agent to solve the cartpole balancing task using the Stable-Baselines3 library. In this tutorial, we will see how to configure the training process to use different RL libraries and different training algorithms.
In the directory scripts/reinforcement_learning, you will find the scripts for
different RL libraries. These are organized into subdirectories named after the library name.
Each subdirectory contains the training and playing scripts for the library.
To configure a learning library with a specific task, you need to create a configuration file
for the learning agent. This configuration file is used to create an instance of the learning agent
and is used to configure the training process. Similar to the environment registration shown in
the Registering an Environment tutorial, you can register the learning agent with the
gymnasium.register method.
The Code#
As an example, we will look at the configuration included for the task Isaac-Cartpole-v0
in the isaaclab_tasks package. This is the same task that we used in the
Training with an RL Agent tutorial.
gym.register(
id="Isaac-Cartpole-v0",
entry_point="isaaclab.envs:ManagerBasedRLEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": f"{__name__}.cartpole_env_cfg:CartpoleEnvCfg",
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpolePPORunnerCfg",
"rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpolePPORunnerWithSymmetryCfg",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
The Code Explained#
Under the attribute kwargs, we can see the configuration for the different learning libraries.
The key is the name of the library and the value is the path to the configuration instance.
This configuration instance can be a string, a class, or an instance of the class.
For example, the value of the key "rl_games_cfg_entry_point" is a string that points to the
configuration YAML file for the RL-Games library. Meanwhile, the value of the key
"rsl_rl_cfg_entry_point" points to the configuration class for the RSL-RL library.
The pattern used for specifying an agent configuration class follows closely to that used for specifying the environment configuration entry point. This means that while the following are equivalent:
Specifying the configuration entry point as a string
from . import agents
gym.register(
id="Isaac-Cartpole-v0",
entry_point="isaaclab.envs:ManagerBasedRLEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": f"{__name__}.cartpole_env_cfg:CartpoleEnvCfg",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpolePPORunnerCfg",
},
)
Specifying the configuration entry point as a class
from . import agents
gym.register(
id="Isaac-Cartpole-v0",
entry_point="isaaclab.envs:ManagerBasedRLEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": f"{__name__}.cartpole_env_cfg:CartpoleEnvCfg",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.CartpolePPORunnerCfg,
},
)
The first code block is the preferred way to specify the configuration entry point. The second code block is equivalent to the first one, but it leads to import of the configuration class which slows down the import time. This is why we recommend using strings for the configuration entry point.
The reinforcement learning entrypoints are configured by default to read the
<library_name>_cfg_entry_point from the kwargs dictionary to retrieve the configuration instance.
For instance, the following code block shows how the Stable-Baselines3 training implementation reads the configuration instance:
Code for train_sb3.py with SB3
1# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
2# All rights reserved.
3#
4# SPDX-License-Identifier: BSD-3-Clause
5
6"""Stable-Baselines3 training logic for the unified reinforcement learning entrypoint."""
7
8from __future__ import annotations
9
10import argparse
11import contextlib
12import logging
13import os
14import random
15import signal
16import sys
17import time
18from datetime import datetime
19from pathlib import Path
20
21from common import (
22 add_common_train_args,
23 add_isaaclab_launcher_args,
24 apply_env_overrides,
25 configure_io_descriptors,
26 create_isaaclab_env,
27 dump_train_configs,
28 enable_cameras_for_video,
29 set_hydra_args,
30 wrap_record_video,
31)
32
33import isaaclab_tasks # noqa: F401
34
35logger = logging.getLogger(__name__)
36
37# PLACEHOLDER: Extension template (do not remove this comment)
38with contextlib.suppress(ImportError):
39 import isaaclab_tasks_experimental # noqa: F401
40
41
42def _cleanup_pbar(*args):
43 """Stop training and clean up rich progress bars on Ctrl+C."""
44 import gc
45
46 tqdm_objects = [obj for obj in gc.get_objects() if "tqdm" in type(obj).__name__]
47 for tqdm_object in tqdm_objects:
48 if "tqdm_rich" in type(tqdm_object).__name__:
49 tqdm_object.close()
50 raise KeyboardInterrupt
51
52
53def _parse_args(argv: list[str]) -> argparse.Namespace:
54 """Parse Stable-Baselines3 training arguments."""
55 parser = argparse.ArgumentParser(description="Train an RL agent with Stable-Baselines3.")
56 add_common_train_args(
57 parser,
58 agent_default="sb3_cfg_entry_point",
59 agent_help="Name of the RL agent configuration entry point.",
60 include_distributed=False,
61 )
62 parser.add_argument("--log_interval", type=int, default=100_000, help="Log data every n timesteps.")
63 parser.add_argument("--checkpoint", type=str, default=None, help="Continue the training from checkpoint.")
64 parser.add_argument(
65 "--keep_all_info",
66 action="store_true",
67 default=False,
68 help="Use a slower SB3 wrapper but keep all the extra training info.",
69 )
70 from isaaclab_tasks.utils import setup_preset_cli
71
72 add_isaaclab_launcher_args(parser)
73 # setup_preset_cli registers preset-selection help text + runs parse_known_args; the
74 # physics=/renderer=/presets= tokens pass through the remainder for hydra to parse later.
75 args_cli, hydra_args = setup_preset_cli(parser, argv)
76 enable_cameras_for_video(args_cli)
77 set_hydra_args(hydra_args)
78 return args_cli
79
80
81def run(argv: list[str]) -> None:
82 """Train a Stable-Baselines3 agent."""
83 import numpy as np
84 from stable_baselines3 import PPO
85 from stable_baselines3.common.callbacks import CheckpointCallback, LogEveryNTimesteps
86 from stable_baselines3.common.vec_env import VecNormalize
87
88 from isaaclab.envs import DirectMARLEnvCfg
89
90 from isaaclab_rl.sb3 import Sb3VecEnvWrapper, process_sb3_cfg
91
92 from isaaclab_tasks.utils import launch_simulation, resolve_task_config
93
94 signal.signal(signal.SIGINT, _cleanup_pbar)
95
96 args_cli = _parse_args(argv)
97 env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent)
98
99 with launch_simulation(env_cfg, args_cli):
100 if args_cli.seed == -1:
101 args_cli.seed = random.randint(0, 10000)
102
103 apply_env_overrides(args_cli, env_cfg)
104 agent_cfg["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["seed"]
105 if args_cli.max_iterations is not None:
106 agent_cfg["n_timesteps"] = args_cli.max_iterations * agent_cfg["n_steps"] * env_cfg.scene.num_envs
107
108 env_cfg.seed = agent_cfg["seed"]
109
110 run_info = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
111 log_root_path = os.path.abspath(os.path.join("logs", "sb3", args_cli.task))
112 print(f"[INFO] Logging experiment in directory: {log_root_path}")
113 print(f"Exact experiment name requested from command line: {run_info}")
114 log_dir = os.path.join(log_root_path, run_info)
115 dump_train_configs(log_dir, env_cfg, agent_cfg)
116
117 command = " ".join(sys.orig_argv)
118 (Path(log_dir) / "command.txt").write_text(command)
119
120 agent_cfg = process_sb3_cfg(agent_cfg, env_cfg.scene.num_envs)
121 policy_arch = agent_cfg.pop("policy")
122 n_timesteps = agent_cfg.pop("n_timesteps")
123
124 configure_io_descriptors(env_cfg, args_cli, logger)
125 env_cfg.log_dir = log_dir
126
127 env = create_isaaclab_env(
128 args_cli.task,
129 env_cfg,
130 args_cli,
131 convert_marl_to_single_agent=isinstance(env_cfg, DirectMARLEnvCfg),
132 )
133 env = wrap_record_video(env, log_dir, args_cli)
134
135 start_time = time.time()
136 env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info)
137
138 norm_keys = {"normalize_input", "normalize_value", "clip_obs"}
139 norm_args = {}
140 for key in norm_keys:
141 if key in agent_cfg:
142 norm_args[key] = agent_cfg.pop(key)
143
144 if norm_args and norm_args.get("normalize_input"):
145 print(f"Normalizing input, {norm_args=}")
146 env = VecNormalize(
147 env,
148 training=True,
149 norm_obs=norm_args["normalize_input"],
150 norm_reward=norm_args.get("normalize_value", False),
151 clip_obs=norm_args.get("clip_obs", 100.0),
152 gamma=agent_cfg["gamma"],
153 clip_reward=np.inf,
154 )
155
156 agent = PPO(policy_arch, env, verbose=1, tensorboard_log=log_dir, **agent_cfg)
157 if args_cli.checkpoint is not None:
158 agent = agent.load(args_cli.checkpoint, env, print_system_info=True)
159
160 checkpoint_callback = CheckpointCallback(save_freq=1000, save_path=log_dir, name_prefix="model", verbose=2)
161 callbacks = [checkpoint_callback, LogEveryNTimesteps(n_steps=args_cli.log_interval)]
162
163 with contextlib.suppress(KeyboardInterrupt):
164 agent.learn(
165 total_timesteps=n_timesteps,
166 callback=callbacks,
167 progress_bar=True,
168 log_interval=None,
169 )
170
171 agent.save(os.path.join(log_dir, "model"))
172 print("Saving to:")
173 print(os.path.join(log_dir, "model.zip"))
174
175 if isinstance(env, VecNormalize):
176 print("Saving normalization")
177 env.save(os.path.join(log_dir, "model_vecnormalize.pkl"))
178
179 print(f"Training time: {round(time.time() - start_time, 2)} seconds")
180 env.close()
The argument --rl_library selects the reinforcement learning library. The --agent
argument selects the library-specific configuration entry point from the kwargs
dictionary, so you can manually specify alternate configuration instances.
The Code Execution#
Since for the cartpole balancing task, RSL-RL library offers two configuration instances,
we can use the --agent argument to specify the configuration instance to use.
Training with the standard PPO configuration:
# standard PPO training ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole --headless \ --run_name ppo
Training with the PPO configuration with symmetry augmentation:
# PPO training with symmetry augmentation ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole --headless \ --agent rsl_rl_with_symmetry_cfg_entry_point \ --run_name ppo_with_symmetry_data_augmentation # you can use hydra to disable symmetry augmentation but enable mirror loss computation ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole --headless \ --agent rsl_rl_with_symmetry_cfg_entry_point \ --run_name ppo_without_symmetry_data_augmentation \ agent.algorithm.symmetry_cfg.use_data_augmentation=false
The --run_name argument is used to specify the name of the run. This is used to
create a directory for the run in the logs/rsl_rl/cartpole directory.