"""Script to train RL agent with RSL-RL.""" """Launch Isaac Sim Simulator first.""" import argparse import sys from pathlib import Path from isaaclab.app import AppLauncher # local imports import cli_args # isort: skip # Prefer this checkout over any other editable ``engineai_lab`` installation. REPO_ROOT = Path(__file__).resolve().parents[1] SOURCE_ROOT = REPO_ROOT / "source" if str(SOURCE_ROOT) not in sys.path: sys.path.insert(0, str(SOURCE_ROOT)) # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") parser.add_argument( "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." ) # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli, hydra_args = parser.parse_known_args() # clear out sys.argv for Hydra sys.argv = [sys.argv[0]] + hydra_args # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import os import torch from datetime import datetime from isaaclab.envs import ( DirectMARLEnv, DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg, multi_agent_to_single_agent, ) from isaaclab.utils.dict import print_dict from isaaclab.utils.io import dump_yaml from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper from isaaclab_tasks.utils import get_checkpoint_path from isaaclab_tasks.utils.hydra import hydra_task_config # Import extensions to set up environment tasks import engineai_lab.tasks # noqa: F401 from rsl_rl.runners.on_policy_runner import OnPolicyRunner torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = False def _restore_training_progress(env, runner, agent_cfg, checkpoint_infos): """Restore environment-side curriculum state after a full RSL-RL resume.""" base_env = env.unwrapped engineai_info = checkpoint_infos.get("engineai_lab", {}) if isinstance(checkpoint_infos, dict) else {} saved_task = engineai_info.get("task") if saved_task is not None and saved_task != args_cli.task: raise ValueError( f"Checkpoint belongs to task {saved_task!r}, not {args_cli.task!r}. " "Use --load_mode finetune for cross-task weight transfer." ) if "common_step_counter" in engineai_info: common_step_counter = int(engineai_info["common_step_counter"]) state_source = "checkpoint metadata" else: common_step_counter = (runner.current_learning_iteration + 1) * agent_cfg.num_steps_per_env state_source = "legacy checkpoint iteration estimate" base_env.common_step_counter = common_step_counter base_env.curriculum_manager.compute(env_ids=None) base_env.command_manager.reset(env_ids=None) print(f"[INFO] Restored common_step_counter={common_step_counter} from {state_source}.") command_term = base_env.command_manager.get_term("base_velocity") if hasattr(command_term.cfg.ranges, "lin_vel_x"): print(f"[INFO] Restored forward command range: {command_term.cfg.ranges.lin_vel_x}") def _attach_training_state_to_checkpoints(env, runner): """Make RSL-RL's periodic saves include the environment curriculum counter.""" base_env = env.unwrapped original_save = runner.save def save_with_training_state(path, infos=None): checkpoint_infos = dict(infos) if isinstance(infos, dict) else {} checkpoint_infos["engineai_lab"] = { "task": args_cli.task, "common_step_counter": int(base_env.common_step_counter), } original_save(path, infos=checkpoint_infos) runner.save = save_with_training_state @hydra_task_config(args_cli.task, "rsl_rl_cfg_entry_point") def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agent_cfg: RslRlOnPolicyRunnerCfg): """Train with RSL-RL agent.""" # override configurations with non-hydra CLI arguments agent_cfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs agent_cfg.max_iterations = ( args_cli.max_iterations if args_cli.max_iterations is not None else agent_cfg.max_iterations ) # set the environment seed # note: certain randomizations occur in the environment initialization so we set the seed here env_cfg.seed = agent_cfg.seed env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: raise ValueError( "Distributed training is not supported when using CPU device. " "Please use GPU device (e.g. --device cuda) for distributed training." ) if args_cli.distributed: env_cfg.sim.device = f"cuda:{app_launcher.local_rank}" agent_cfg.device = f"cuda:{app_launcher.local_rank}" seed = agent_cfg.seed + app_launcher.local_rank env_cfg.seed = seed agent_cfg.seed = seed # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Logging experiment in directory: {log_root_path}") # specify directory for logging runs: {time-stamp}_{run_name} log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if agent_cfg.run_name: log_dir += f"_{agent_cfg.run_name}" log_dir = os.path.join(log_root_path, log_dir) # set the log directory for the environment (works for all environment types) env_cfg.log_dir = log_dir # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) # wrap for video recording # convert to single-agent instance if required by the RL algorithm if isinstance(env.unwrapped, DirectMARLEnv): env = multi_agent_to_single_agent(env) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # create runner from rsl-rl runner = OnPolicyRunner( env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device ) # write git state to logs runner.add_git_repo_to_log(__file__) # save resume path before creating a new log_dir if agent_cfg.resume: # get path to previous checkpoint resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) print(f"[INFO]: Loading model checkpoint from: {resume_path}") if args_cli.load_mode == "finetune": runner.load( resume_path, load_cfg={ "actor": True, "critic": True, "optimizer": False, "iteration": False, "rnd": False, }, ) print("[INFO] Loaded actor/critic weights with a fresh optimizer and curriculum.") else: checkpoint_infos = runner.load(resume_path) _restore_training_progress(env, runner, agent_cfg, checkpoint_infos) print(f"[INFO] Optimizer learning rate after load: {runner.alg.learning_rate:.6g}") _attach_training_state_to_checkpoints(env, runner) # dump the configuration into log-directory dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg) dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg) # dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg) # dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg) # run training runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) # close the simulator env.close() if __name__ == "__main__": # run the main function main() # close sim app simulation_app.close()