Feature ExamplesGeneral Examples
Reinforcement Learning Case (Gym Version)
- Reinforcement Learning Case (Gym Version)
- Overview
- Demo
- Deployment
- Training
Overview
This case briefly introduces how to use Leju's open-source reinforcement learning locomotion control repository kuavo-rl-opensource to train and deploy the Leju Kuavo robot.
Demo
- sim2sim
- sim2real
Deployment
Cloning and Building the Code
git clone -b beta https://gitee.com/leju-robot/kuavo-rl-opensource.git
cd kuavo-rl-opensource/kuavo-robot-deploy/
sudo su
export ROBOT_VERSION=42
source installed/setup.bash
catkin build humanoid_controllersChecking the Relevant Configuration
Check the launch file, located at /home/lab/kuavo-rl-opensource/kuavo-robot-deploy/src/humanoid-control/humanoid_controllers/launch.
- If you are deploying the model to a simulation environment, modify
load_kuavo_mujoco_sim.launch; if you are deploying the model to a real robot, modifyload_kuavo_real.launch:
# 确保程序使用的是skw_rl_param.info
<arg name="rl_param" default="$(find humanoid_controllers)/config/kuavo_v$(arg robot_version)/rl/skw_rl_param.info"/>Check the skw_rl_param.info file, located at /home/lab/kuavo-rl-opensource/kuavo-robot-deploy/src/humanoid-control/humanoid_controllers/config/kuavo_v42/rl:
- Change the original
.onnxmodel referenced in it to the newly generated model.
# 原有代码为:
networkModelFile /42_model_skw_0115_p120.onnx;
# 将其修改为:
# 确保程序使用的模型是您训练生成的:
networkModelFile /your_new_model.onnx;- Our code repository provides a model trained based on this case,
42_model_skw_0115_p120.onnx, which can be used directly.
H12 Remote Controller Instructions
- Startup Instructions
-
Real Robot Startup
- Before starting, make sure the
Ekey is at the far left and theFkey is at the far right. - After the robot retracts its legs, flipping the
Fkey to the far left makes it stand up. - After the robot is standing, press the corresponding keys in sequence to enter reinforcement learning mode and to unlock. The robot can then be controlled with the joystick.
- Flipping the
Ekey to the far right stops the program (note that the robot will not squat down automatically at this point).
- Before starting, make sure the
-
H12 remote controller key positions for reinforcement learning: Go to
-
Program Startup
#新开终端
cd kuavo-rl-opensource/kuavo-robot-deploy
sudo su
export ROBOT_VERSION=42
source devel/setup.bash
# 仿真
roslaunch humanoid_controllers load_kuavo_mujoco_sim.launch joystick_type:=sim # 启动rl控制器、wbc、仿真器(默认 sim_input_mode:=keyboard)。
# 如需 GUI 虚拟手柄输入,请显式指定:
# roslaunch humanoid_controllers load_kuavo_mujoco_sim.launch joystick_type:=sim sim_input_mode:=gui
# 实物
roslaunch humanoid_controllers load_kuavo_real.launch joystick_type:=h12 # 可以选择cali:=true和cali_arm:=true进行校准启动,但校准启动不会自动缩腿,需要把F键拨到最左边两次,第一次是执行缩腿,第二次是执行站立 。Note: Start either the simulation or the real robot, not both.
joystick_type:=simuses keyboard input by default (sim_input_mode:=keyboard); GUI mode requires explicitly passingsim_input_mode:=gui.
Motor Control Topic Instructions
- Motor control commands are published via the ROS topic
/joint_cmd, with the message typekuavo_msgs::jointCmd. Thecontrol_modesfield determines whether torque control (force control) or position control is used. The implementation is as follows:
1. Control Command Output
- Message structure: The
jointCmdmessage contains the following fields:
| Field | Type | Description |
|---|---|---|
| joint_q | float64[] | Target joint position (rad) |
| joint_v | float64[] | Target joint velocity (rad/s) |
| tau | float64[] | Target joint torque (Nm) |
| tau_max | float64[] | Maximum joint torque |
| tau_ratio | float64[] | Torque coefficient |
| joint_kp | float64[] | kp parameter |
| joint_kd | float64[] | kd parameter |
| control_modes | int32[] | Control mode (0 - torque, 1 - velocity, 2 - position) |
- Publishing logic: In the
update()function, the message is filled according to the control mode and published to/joint_cmd.
2. Control Mode Selection
- Torque control (CST):
control_modes=0 - The
tauvalue is sent directly to the low-level driver. - Example code snippet:
jointCmdMsg.control_modes.push_back(0); // CST模式
jointCmdMsg.tau.push_back(calculated_torque);- Position control (CSP):
control_modes=2 - The target position
joint_qand PID parameterskp/kdare sent, and the low-level driver performs closed-loop control. - Example code snippet:
jointCmdMsg.control_modes.push_back(2); // CSP模式
jointCmdMsg.joint_q.push_back(target_position);
jointCmdMsg.joint_kp.push_back(kp_value);3. Mixed Control Implementation
- Mode switching: The control mode of each joint is configured through the
JointControlMode_array. - RL controller: Torque or position commands are selected according to the policy output, for example:
if (JointControlMode_(i) == 0) { // 力矩控制
cmd[i] = kp*(目标位置 - 当前位置) - kd*速度;
} else if (JointControlMode_(i) == 2) { // 位置控制
发送目标位置和PID参数;
}4. Low-Level Hardware Interaction
- Driver configuration: The driver needs to switch its control mode (e.g., CSP/CST) according to
control_modesand apply the corresponding PD parameters.
Summary
- Force control: Joint torque values are sent directly, and the driver controls the current in a closed loop.
- Position control: The target position and PD parameters are sent, and the driver controls the position in a closed loop.
- Mixed control: Force/position control is mixed across joints via the independent
control_modesof each joint.
Analysis of the PD Control Implementation
1. Parameter Configuration Module
1.1 Loading Joint Parameters
// 从referenceFile加载主关节参数
loadData::loadEigenMatrix(referenceFile, "jointKp", jointKp_);
loadData::loadEigenMatrix(referenceFile, "jointKd", jointKd_);
// 头部关节特殊配置
if (headNum_ > 0) {
loadData::loadEigenMatrix(referenceFile, "head_kp_", head_kp_);
loadData::loadEigenMatrix(referenceFile, "head_kd_", head_kd_);
}- Parameter dimensions: (jointNum_ + jointArmNum_), supporting independent configuration for different joints
- Special handling for the head: head_kp_ and head_kd_ are loaded separately
1.2 Filter Parameters
// 关节指令滤波器配置
Eigen::VectorXd jointCmdFilterCutoffFreq_(jointNum_ + jointArmNum_);
loadData::loadEigenMatrix(rlParamFile, "jointCmdFilterCutoffFreq", jointCmdFilterCutoffFreq_);
jointCmdFilter_.setParams(dt, jointCmdFilterCutoffFreq_);- Smooths the RL output actions to prevent abrupt torque changes
2.1 Joint Torque Calculation in the RL Controller
PD Torque Calculation in the RL Controller
// updateRLcmd() 函数中的 PD 计算
jointTor_(i) = jointKp_(i) * (local_action[i] * actionScale_ - jointPos_[i] + defalutJointPos_[i]) - jointKd_(i) * jointVel_[i];
//其中(local_action[i] * actionScale_ - jointPos_[i] + defalutJointPos_[i])是关节位置误差,-jointVel_[i]是速度误差-
Formula:

-
actionScale_ scales the RL output action values
-
clipActions_ limits the action range to prevent excessively large values
Independent PD Control of the Head Joints
// 头部力矩计算
vector_t head_feedback_tau = head_kp_.cwiseProduct(desire_head_pos_ - sensor_data_head_.jointPos_)
+ head_kd_.cwiseProduct(-sensor_data_head_.jointVel_);-
Formula:

-
Independent of the body control loop and uses sensor feedback data directly
Program Reference
- Path:
<kuavo-rl-opensource>/src/humanoid-control/humanoid_controllers/src/humanoidController.cpp
Main Control Flow
- Start the controller:
- Initialize the hardware interface, WBC, state estimator, etc.
- Start the keyboard control thread and the inference thread.
- State estimation:
- Obtain the latest sensor data from the sensor data buffer.
- Update the robot state using the state estimator.
- Control mode selection:
- Select the control mode (WBC or RL) based on the current state and user input.
- Control computation:
- If WBC mode is selected, call
wbc_->updateto compute joint torques. - If RL mode is selected, call the neural network model to generate control commands.
- If WBC mode is selected, call
- Command publishing:
- Publish the control commands to the hardware interface.
- Loop update:
- Continuously repeat the process of state estimation, control computation, and command publishing.
Training
Installation
isaacgym
wget https://developer.nvidia.com/isaac-gym-preview-4
tar -xvzf isaac-gym-preview-4 #将名字改为 isaacgym 并存放在'kuavo-robot-train'同级目录下conda
MiniConda is recommended, as it is lightweight and more flexible to use.
#安装
mkdir -p ~/miniconda3
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh
bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3
rm ~/miniconda3/miniconda.sh
#初始化
~/miniconda3/bin/conda init --all
source ~/.bashrcConfiguring the Environment
conda create -n humanoid-gym-op python=3.8
conda activate humanoid-gym-op
cd kuavo-rl-opensource/kuavo-robot-train
pip install -e ../isaacgym/python
pip install -e .Training and Playing
Example
python scripts/train.py --task=kuavo_s42_sk_ppo --run_name v1 --headless --num_envs 4096
python scripts/play.py --task=kuavo_s42_sk_ppo --run_name v1Continue training from a specified .pt file
python scripts/train.py --task=kuavo_s42_sk_ppo --run_name v1 --headless --num_envs 4096 --resume --load_run Feb07_11-27-10_v1 --checkpoint 0 #该例子表示文件保存在'kuavo-robot-train/logs/Kuavo_s42_sk_ppo/Feb07_11-27-10_v1'目录下,选择了model_0.pt文件进行继续训练,headless选项关闭了GUI显示。
python scripts/play.py --task=kuavo_s42_sk_ppo --run_name v1 --load_run Feb07_11-27-10_v1 --checkpoint 0Parameter Description
Custom Parameter Details
1. Training Task Control
| Parameter | Type | Default | Key Function | Usage Example |
|---|---|---|---|---|
--task | str | XBotL_free | Defines the training task type | Switch robot model (e.g. XBotL_walking) |
--max_iterations | int | - | Maximum number of training iterations | Limit the training duration |
--resume | flag | False | Resume training from a checkpoint | Continue after an unexpected training interruption |
2. Experiment Version Management
| Parameter | Type | Key Function | Data Storage Logic |
|---|---|---|---|
--experiment_name | str | Identifies the experiment project | Corresponds to a folder under experiments/ |
--run_name | str | Identifier for a single run | Compare different parameters within the same experiment |
--load_run | str | Load a previous run record | -1 means load the latest run |
--checkpoint | int | Specify the model checkpoint | -1 loads the latest checkpoint |
3. Hardware Resource Configuration
| Parameter | Type | Default | Technical Details | Typical Configuration |
|---|---|---|---|---|
--rl_device | str | cuda:0 | Device on which the RL algorithm runs | cuda:1 selects the second GPU |
--num_envs | int | - | Number of parallel environments | 4096 (adjust according to GPU memory) |
--horovod | flag | False | Enable distributed training | Used for multi-GPU training |
4. Visualization and Debugging
| Parameter | Type | Key Function | Typical Usage Scenario |
|---|---|---|---|
--headless | flag | Disable graphical rendering | Server environments without a display |
--seed | int | Fix the random seed | Ensures experiment reproducibility |
5. Parameter Priority Logic
- Command-line arguments > configuration file > code defaults