2 Training and Model Export

This section explains how to launch PPO training under Isaac Lab + rsl_rl 5.0, understand the training recipe, select a suitable model from the checkpoints produced during training, and export a deployable policy.onnx (and a JIT-format policy.pt).

Unless stated otherwise, all commands below are run from the code root directory (the root of the SDK main repo).

2.1 Overview: the training-to-export pipeline

        flowchart TD
    cfg["velocity_env_cfg.py<br/>Task / Reward Config"]
    train["train.py"]
    ckpt["checkpoint<br/>model_*.pt<br/>Produced by PPO Training"]
    play["play.py<br/>Load final / latest checkpoint<br/>Auto Export"]
    best["export_best.py<br/>Select best checkpoint<br/>Re-export"]
    exported["policy.onnx<br/>policy.pt"]

    cfg --> train
    train -- "PPO Training (rsl_rl 5.0)" --> ckpt
    ckpt -- "final / latest" --> play
    ckpt -- "Select best by moving average" --> best
    play --> exported
    best --> exported

    

2.2 Launching Training

Single Training Command

conda activate isaaclab
export ISAACLAB_PATH=<isaaclab-path>   # Point to the local Isaac Lab install directory; fill in the actual path
cd extra/mc-rl/rl/agibot_rl_lab
python scripts/rsl_rl/train.py --task Agibot-X2-29dof-Velocity --num_envs 4096 --headless

Argument

Meaning

Notes

--task Agibot-X2-29dof-Velocity

X2 29-DoF velocity task (registered in agibot_rl_lab.tasks)

Required; valid values come from the registered tasks

--num_envs 4096

Number of parallel environments

Uses the config default if omitted

--headless

Headless (no-render) mode (an AppLauncher argument)

Always enable during training to save GPU memory and compute

--max_iterations

Upper limit on training iterations

Uses the PPO config default max_iterations=50000 if omitted

--seed / --distributed

Random seed / multi-GPU

Optional

Training Duration and Log Directory

  • Duration: about 15–19 hours (RTX 5090, iterating to 40k–50k).

  • Log output directory:

extra/mc-rl/rl/agibot_rl_lab/logs/rsl_rl/agibot_x2_29dof_velocity/<timestamp_runname>/

Here <timestamp> is YYYY-MM-DD_HH-MM-SS. This directory is gitignored locally and not committed; it contains model_*.pt (checkpoints), params/ (exported config copies such as env.yaml / agent.yaml), and TensorBoard event files.

  • View the training curves:

tensorboard --logdir extra/mc-rl/rl/agibot_rl_lab/logs/rsl_rl/agibot_x2_29dof_velocity

2.3 Training Recipe

Right at the top, velocity_env_cfg.py does from unitree_rl_lab.tasks.locomotion import mdp, directly reusing the mdp of unitree_rl_lab under extra/mc-rl/third_party/, and on that basis adjusts the reward weights (plus one observation scale and one termination threshold) and robot-related parameters.

Note

unitree_rl_lab lives under extra/mc-rl/third_party/; X2 only reuses it and does not modify its source. All X2 code is packaged separately as agibot_rl_lab, reusing it by import-ing its mdp without modifying the source.

Tip

Besides reusing the upstream mdp, you can also write local mdp extension functions (custom rewards / observations / events, etc.) inside agibot_rl_lab and reference them in the corresponding Term of velocity_env_cfg.py — without modifying the upstream unitree_rl_lab. The X2 recipe uses exactly this approach to add training-time IMU pitch bias domain randomization on the projected-gravity observation (the local extension projected_gravity_with_bias).

Reward Weights and Key Parameters

The main reward weights for the X2 velocity locomotion task (configured in velocity_env_cfg.py):

Item

Value

Purpose

track_lin_vel_xy (std)

√0.1 ≈ 0.316

Linear-velocity tracking (smaller std = stricter tracking, favoring low-speed walking)

track_ang_vel_z (weight)

1.0

Yaw angular-velocity tracking

base_angular_velocity (ang_vel_xy_l2)

−0.15

Suppresses torso wobble

action_rate (action_rate_l2)

−0.1

Smooths actions and suppresses jitter

joint_deviation_arms (joint_deviation_l1)

−0.3

Constrains the arms and reduces irrelevant swinging

base_height (target)

0.68

Target pelvis standing height

Termination base_height (min)

0.3

If the pelvis drops below this height, a fall is detected and the episode terminates early

base_ang_vel (obs scale)

0.25

Observation normalization; consistent between training and deployment

The remaining reward terms use the mdp defaults: alive 0.15, lin_vel_z_l2 −2.0, joint_acc −2.5e-7, energy −2e-5, flat_orientation −5.0, base_height weight −10, gait 0.5, feet_clearance 1.0, undesired_contacts −1, and so on.

Joint KP/KD and Effort

Group

Joint

Count

Kp

Kd

effort

Leg

hip_pitch

2

120

5

120

Leg

hip_roll

2

100

4

120

Leg

hip_yaw

2

100

4

120

Leg

knee

2

150

5

120

Ankle

ankle_pitch

2

40

2

36

Ankle

ankle_roll

2

40

2

24

Waist

waist_yaw

1

40.18

2.56

120

Waist

waist_pitch/roll

2

200

2

48

Shoulder / elbow

shoulder_*/elbow

8

50

3

24–36

Wrist

wrist_*

6

20

2

4.8–24

Head

head_yaw/pitch

2

0

2

— (the URDF has 31 joints in total but only 29 are driven; the head does not participate in RL. KD=2 is merely a placeholder in joint_gains.yaml; the RL actuator does not apply it to the head)

  • KP/KD source: from the single source of truth extra/mc-rl/x2_config/joint_gains.yaml (the rl_gains section), loaded by load_gains() in extra/mc-rl/x2_config/joint_gains.py. Training (agibot.py), sim2sim, and deployment (extra/mc-rl/x2_deploy_pkg/deploy_x2.py) all read from this YAML, so a change in one place takes effect in all three. These are simulation values, not real-robot measurements; once real-robot calibration values are obtained, editing this YAML and retraining is enough.

  • effort source: the AgiBot X2 URDF and MJCF.

2.4 Checkpoint Selection

  • Training to the final iteration (e.g. 50k) is not the same as optimal: the reward curve often degrades late in training, and the best checkpoint is usually found mid-run.

  • How to pick the best: export_best.py has it built in — it automatically selects and exports the best by the moving average of Train/mean_reward (see “Method 2” below); alternatively, look near the moving-average peak of the reward curve in TensorBoard and manually pick the corresponding model_<iter>.pt.

  • Deployment principle: export from the best checkpoint, not the final one. The final checkpoint is auto-loaded by play.py and is suitable for quick sim replay; the production deployment model should be exported by selecting the best with export_best.py, per Method 2 in “Model Export”.

2.5 Batch Experiments

extra/mc-rl/rl/train/batch_train.py is a batch training orchestrator: internally it loops over the train.py from “Launching Training” above, automatically running multiple sets of reward weights in sequence with no human supervision (designed to switch between experiment groups automatically, each about 15h). In short, use train.py for a single run and batch_train.py to sweep weights in batches; the latter is a wrapper around the former.

Which groups actually run is defined by the EXPERIMENTS list in the script — it gives different combinations of four weight terms (joint_deviation_arms / track_ang_vel_z / base_angular_velocity / action_rate). The default example bundled with the script is the following 4 groups:

Experiment

joint_deviation_arms

track_ang_vel_z

base_angular_velocity

action_rate

Description

exp-E

−0.25

0.75

−0.10

−0.08

Milder arm constraint and yaw tracking

exp-F

−0.30

1.00

−0.15

−0.10

Medium strength across the board (matches the default recipe in “Reward Weights and Key Parameters” above)

exp-G

−0.25

1.00

−0.10

−0.08

Strong yaw tracking, the rest milder

exp-H

−0.30

1.00

−0.15

−0.08

Medium-strength combination

The above is the default example configuration bundled with the script, not a fixed baseline; to add, remove, or modify experiments, just edit the EXPERIMENTS list at the top of batch_train.py. Any reward terms not listed keep the defaults from “Reward Weights and Key Parameters” above.

Key mechanics:

  1. The script directly rewrites the weights in velocity_env_cfg.py before training, using regex substitution on the four weights track_ang_vel_z / base_angular_velocity / action_rate / joint_deviation_arms.

  2. Before rewriting, it backs up to velocity_env_cfg.py.bak, and automatically restores the original file after all runs finish.

  3. After rewriting each group, verify_config checks that the weights were written; if the check fails, that group is skipped.

  4. Each group internally invokes the train.py from “Launching Training” above automatically with MAX_ITER = 40000 (no manual execution needed), equivalent to:

# For illustration only: batch_train.py runs this command automatically for each experiment; no need to run it by hand
python scripts/rsl_rl/train.py --task Agibot-X2-29dof-Velocity --headless --max_iterations 40000

In practice you only run the batch script itself, and it completes training group by group per the mechanism above:

conda activate isaaclab
export ISAACLAB_PATH=<isaaclab-path>   # Point to the local Isaac Lab install directory; fill in the actual path
nohup python extra/mc-rl/rl/train/batch_train.py > batch_train.log 2>&1 &

Warning

This script temporarily modifies velocity_env_cfg.py; if the process is force-killed midway it may not have restored the file, and you must manually restore it from velocity_env_cfg.py.bak. The EXPERIMENTS list (experiment names and weights) is hard-coded in the script; to change experiments, edit that list directly.

2.6 Model Export

Model export produces two formats at once: policy.onnx (ONNX, what this project actually uses for deployment, loaded by onnxruntime) and policy.pt (JIT / TorchScript, an alternative format for runtimes such as LibTorch).

Method 1: Automatic Export with play.py

cd extra/mc-rl/rl/agibot_rl_lab
python scripts/rsl_rl/play.py --task Agibot-X2-29dof-Velocity --headless --num_envs 1 --export-only
  • Automatically loads the checkpoint of the task’s latest run (you can also specify a particular .pt with --checkpoint <path>).

  • Exports to logs/rsl_rl/agibot_x2_29dof_velocity/<run>/exported/policy.onnx, and also produces the JIT-format policy.pt.

  • Internal flow: after runner.load(ckpt), it takes runner.alg.actor (an MLPModel), generates an ONNX wrapper via policy_nn.as_onnx(), then exports with torch.onnx.export(opset_version=18); the JIT is exported via policy_nn.as_jit() and torch.jit.script.

  • With --export-only, it exits right after export, skipping the visualization loop; without it, it enters real-time replay (combine with --real-time to observe the gait).

Method 2: Manually Export a Specified Best Checkpoint

When the optimal checkpoint is not the final one, use extra/mc-rl/rl/train/export_best.py. This script does best-selection + export in one shot: it picks the best checkpoint from the TensorBoard logs by Train/mean_reward (moving average), then rebuilds the MLP from its .pt and exports. The export directory is automatically set to exported/ under that run:

conda activate isaaclab

# Usage 1: auto-select — with no arguments, automatically locate the latest run and export its best checkpoint
python extra/mc-rl/rl/train/export_best.py

# Usage 2: specify a run directory to export that run's best checkpoint
python extra/mc-rl/rl/train/export_best.py <run_dir>

# Usage 3: skip selection and directly export a specified checkpoint
python extra/mc-rl/rl/train/export_best.py <run_dir> model_44100.pt

Argument descriptions:

Argument

Default

Description

log_dir (positional)

Auto-locates the latest run

Path to the training run directory; if omitted, picks the most recently modified run under extra/mc-rl/rl/agibot_rl_lab/logs/rsl_rl

model (positional)

Auto-selects the best

Specify a particular checkpoint filename (e.g. model_44100.pt); when given, selection is skipped and it exports directly

--top

5

Prints the top-N checkpoints by reward for comparison

--smooth

5

Moving-average window of the reward curve used for best selection

--iter

best

Additionally prints detailed metrics for that iteration (defaults to the best’s)

Policy Network Architecture Reference

To rebuild the network manually, you need to know the structure of the policy (actor) in the checkpoint. Its weights live in ckpt["actor_state_dict"] with the prefix mlp., and overall it is a 4-layer MLP:

500 (observation) → 512 → 256 → 128 → 29 (action), with ELU activation on the hidden layers (hidden dims [512, 256, 128]).

Here distribution.std_param (dimension 29) is the PPO exploration noise; it is not needed for deployment and should be discarded when exporting manually.

2.7 Troubleshooting

Problem

Cause

Solution

rsl_rl 5.0 incompatibility

ActorCritic was refactored into MLPModel

The PPO config migrates to RslRlMLPModelCfg; train.py / play.py call handle_deprecated_rsl_rl_cfg(agent_cfg, "5.0.1"). Note that old ActorCritic checkpoints are not interoperable with the new structure; externally you must use rsl_rl 5.0.1

ONNX export IndexError

MLPModel.forward() requires a TensorDict input

Use the built-in MLPModel.as_onnx() method (see “Method 1” above); do not export forward directly

obs history concatenated incorrectly

Per-frame concatenation causes abnormal sim2sim behavior

Concatenate per-term: each observation term maintains its own history buffer

After exporting policy.onnx, proceed to MuJoCo Sim2Sim Validation.