Kuavo Docs
Feature ExamplesGeneral Examples

Reinforcement Learning Case (Gym Version)

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_controllers

Checking 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, modify load_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 .onnx model 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 E key is at the far left and the F key is at the far right.
      • After the robot retracts its legs, flipping the F key 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 E key to the far right stops the program (note that the robot will not squat down automatically at this point).
    • 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:=sim uses keyboard input by default (sim_input_mode:=keyboard); GUI mode requires explicitly passing sim_input_mode:=gui.

Motor Control Topic Instructions

  • Motor control commands are published via the ROS topic /joint_cmd, with the message type kuavo_msgs::jointCmd. The control_modes field determines whether torque control (force control) or position control is used. The implementation is as follows:

1. Control Command Output

  • Message structure: The jointCmd message contains the following fields:
FieldTypeDescription
joint_qfloat64[]Target joint position (rad)
joint_vfloat64[]Target joint velocity (rad/s)
taufloat64[]Target joint torque (Nm)
tau_maxfloat64[]Maximum joint torque
tau_ratiofloat64[]Torque coefficient
joint_kpfloat64[]kp parameter
joint_kdfloat64[]kd parameter
control_modesint32[]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 tau value 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_q and PID parameters kp/kd are 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_modes and 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_modes of 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: PD 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: Head PD 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

  1. Start the controller:
    • Initialize the hardware interface, WBC, state estimator, etc.
    • Start the keyboard control thread and the inference thread.
  2. State estimation:
    • Obtain the latest sensor data from the sensor data buffer.
    • Update the robot state using the state estimator.
  3. Control mode selection:
    • Select the control mode (WBC or RL) based on the current state and user input.
  4. Control computation:
    • If WBC mode is selected, call wbc_->update to compute joint torques.
    • If RL mode is selected, call the neural network model to generate control commands.
  5. Command publishing:
    • Publish the control commands to the hardware interface.
  6. 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 ~/.bashrc

Configuring 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 v1

Continue 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 0

Parameter Description

Custom Parameter Details

1. Training Task Control
ParameterTypeDefaultKey FunctionUsage Example
--taskstrXBotL_freeDefines the training task typeSwitch robot model (e.g. XBotL_walking)
--max_iterationsint-Maximum number of training iterationsLimit the training duration
--resumeflagFalseResume training from a checkpointContinue after an unexpected training interruption
2. Experiment Version Management
ParameterTypeKey FunctionData Storage Logic
--experiment_namestrIdentifies the experiment projectCorresponds to a folder under experiments/
--run_namestrIdentifier for a single runCompare different parameters within the same experiment
--load_runstrLoad a previous run record-1 means load the latest run
--checkpointintSpecify the model checkpoint-1 loads the latest checkpoint
3. Hardware Resource Configuration
ParameterTypeDefaultTechnical DetailsTypical Configuration
--rl_devicestrcuda:0Device on which the RL algorithm runscuda:1 selects the second GPU
--num_envsint-Number of parallel environments4096 (adjust according to GPU memory)
--horovodflagFalseEnable distributed trainingUsed for multi-GPU training
4. Visualization and Debugging
ParameterTypeKey FunctionTypical Usage Scenario
--headlessflagDisable graphical renderingServer environments without a display
--seedintFix the random seedEnsures experiment reproducibility
5. Parameter Priority Logic
  • Command-line arguments > configuration file > code defaults