RaisimGymTorch
RaisimGymTorch trains control policies with reinforcement learning in RaiSim. It steps hundreds or thousands of copies of an environment in parallel in C++, with OpenMP, and hands their observations to Python as one batch, through nanobind. A small PyTorch PPO implementation comes with it, but the environments work with any framework that can exchange NumPy arrays. On one desktop it collects hundreds of thousands of environment steps per second, and tens of thousands with a GPU-rendered depth image for every robot.
rsg_anymal_depth: ANYmal walks over stairs, gaps and blocks from its front depth camera alone (top right), with a policy trained in about 45 minutes on a desktop.
Overview
An environment is a C++ class, Environment.hpp, that owns one RaiSim World and defines its observation, its reward and when an episode ends. Every directory under raisimGymTorch/raisimGymTorch/env/envs holds one, together with its cfg.yaml and its Python scripts, and the build compiles each into a Python module of the same name (from raisimGymTorch.env.bin import rsg_anymal).
VectorizedEnvironment(VectorizedEnvironment.hpp) createsnum_envscopies of the environment and steps, resets and observes them in parallel with OpenMP.raisim_gym.cppexposes it to Python with nanobind.RaisimGymVecEnv(RaisimGymVecEnv.py) wraps the module with NumPy arrays that it allocates once and the C++ module fills in place.runner.pytrains: it asks the policy for the actions of all environments in one forward pass, steps them with one call, and updates the policy with PPO (raisimGymTorch/algo/ppo).
Each control step is therefore one call from Python, with an N x A array of actions in and N x D observations, N rewards and N episode ends out, whatever the number of environments N. Batching and resource sharing explains what happens inside that call and how the environments share their robot model, terrains and renderer.
Installation
RaiSim, rayrai, Eigen and nanobind come with raisim2Lib. In addition, you need:
- Python 3.9 or newer, with its development headers, in a venv or conda environment; CMake 3.10 or newer; and a C++20 compiler.
- PyTorch (https://pytorch.org/). To use the GPU, also install the CUDA version that PyTorch recommends.
- OpenMP on Linux and Windows (with Clang, install
libomp-dev). On macOS, OpenMP is used when available (libomp); otherwise RaisimGymTorch builds without it and runs the environments one after another. ffmpegonPATHto record evaluation videos.
From the raisimGymTorch directory:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install -e . --no-build-isolationThis builds every environment in Release mode and installs the package in editable mode; --no-build-isolation builds against the PyTorch of the active environment. Run the same pip install again after changing C++ code. On macOS, source the package environment first so that Python can load the RaiSim and rayrai libraries:
cd ..
source ./raisim_env.sh
cd raisimGymTorch
pip install -e . --no-build-isolationIf ../raisim or ../rayrai is missing, CMake downloads the matching release package, for example macos-arm64 on Apple Silicon (including Rosetta shells) and macos-x86_64 on Intel when that asset is available. To build against other RaiSim and rayrai installations, set RAISIMGYM_RAISIM_ROOT and RAISIMGYM_RAYRAI_ROOT before pip install.
Environments
Three ANYmal environments come with RaisimGymTorch, from a minimal example to a complete recipe for walking from depth images:
| Environment | Task | Observation | Shared | Training |
|---|---|---|---|---|
rsg_anymal | run forward on flat ground | 34 robot states | robot model | 75 s |
rsg_anymal_terrain | run forward over rough terrain | 33 robot states, 35 terrain heights | robot model, terrain | 2 min |
rsg_anymal_depth | follow commands over 8 kinds of terrain | 48 robot states and command, then 270 terrain heights (teacher) or a depth image (student) | robot model, 80 terrains, render meshes | 36 + 10 min |
Training times are for 1000 iterations of the first two and for the teacher and the student of the third, on an Intel Core Ultra 7 265K (20 cores) with an RTX 5070. Every runner saves a checkpoint and records a video of the first environment every few hundred iterations (see Evaluation videos).
rsg_anymal: the minimal example
python raisimGymTorch/env/envs/rsg_anymal/runner.py
python raisimGymTorch/env/envs/rsg_anymal/runner.py --mode retrain --weight <run dir>/full_N.pt
python raisimGymTorch/env/envs/rsg_anymal/tester.py --weight <run dir>/full_N.ptrsg_anymal is the template to copy for a new environment. Its Environment.hpp is about 200 lines:
- The constructor creates the
World, adds the ground and an ANYmal from a robot model that all environments share (see Sharing resources), sets the PD gains and declares the observation and action sizes and the reward terms ofcfg.yaml. step()turns the 12 actions into joint position targets (the nominal stance plus 0.3 rad per unit of action), integrates the World for one control period (4 physics steps of 2.5 ms), and records the reward: forward speed (up to 4 m/s) minus a torque cost.isTerminalState()ends the episode with a penalty of -10 when anything but the lower legs (which carry the feet) touches the ground.
100 environments run 4 s episodes; PPO trains at about 670,000 steps per second, 0.06 s per iteration, and the robot runs within a few hundred iterations. Because the reward asks only for speed, the policy runs with a fast bound rather than a trot: rsg_anymal_depth shows the reward terms a natural gait needs. tester.py replays a checkpoint in one environment, for watching in a viewer, and benchmark_rollout.py measures the rollout speed of the Python and C++ evaluation paths against the number of threads.
rsg_anymal_terrain: one terrain for all environments
python raisimGymTorch/env/envs/rsg_anymal_terrain/runner.pyThe same task on a 40 m fractal terrain. All environments stand on one height map: the environment generates it once as a HeightMapResource and each World adds a HeightMap that only references its samples and collision tiles, so the terrain takes the memory of one height map however many environments run. Every terrain/randomize_every_n iterations (10), curriculum_callback() moves all environments onto a new terrain, whose noise frequency, height scale and step size are drawn from the ranges in cfg.yaml; terrain k depends only on terrain/seed and k, so every environment derives the same one. Robots start at random positions and headings in the central half of the terrain. The observation replaces the base height with a 7 x 5 grid of base heights above the terrain around the robot, turned with its heading, and an episode also ends, without a penalty, 1 m from the terrain edge. It trains at about 360,000 steps per second, against 670,000 for rsg_anymal on flat ground.
rsg_anymal_depth: walking on rough terrain from depth images
rsg_anymal_depth trains ANYmal C to follow velocity commands over rough terrain using its front depth camera. It follows the two-stage recipe of Agarwal et al. 2022 and Cheng et al. 2023: a teacher learns with PPO from terrain heights that a real robot cannot sense, and a student learns to act as the teacher does from what a real robot has, proprioception and a depth camera.
# 1. Teacher: PPO on proprioception and 270 terrain heights around the robot
python raisimGymTorch/env/envs/rsg_anymal_depth/runner.py
# 2. Student: proprioception and 64 x 48 depth images, trained by DAgger
python raisimGymTorch/env/envs/rsg_anymal_depth/student.py --teacher <teacher dir>/full_3000.pt
# Evaluate on every terrain level, or on one, at a fixed speed, with a video and the camera's view
python raisimGymTorch/env/envs/rsg_anymal_depth/student.py --mode test --weight <student dir>/student_2000.pt
python raisimGymTorch/env/envs/rsg_anymal_depth/student.py --mode test --weight <student dir>/student_2000.pt \
--level 9 --command 0.8 --video level9.mp4 --depth-png level9_depth.png
# Check every observation entry, reward term, statistic, reset and depth image
python raisimGymTorch/env/envs/rsg_anymal_depth/check.py --teacher <teacher dir>/full_3000.ptrunner.py, student.py and check.py share common.py, which loads cfg.yaml, creates environments and loads the teacher.

One moment on stairs. Top: the robot, with the student's depth image in the corner. Bottom left: what the teacher sees, 270 terrain heights around the base, from 0.5 m behind it to 1.2 m ahead and 0.7 m to each side. Bottom right: what the student sees instead, the 64 x 48 depth image of its front camera (near is bright).
Both see the same 48 proprioceptive values: the gravity direction, the base velocities, the command, the joint positions and velocities and the previous action. The teacher's terrain heights come from HeightMap::getHeight() at an 18 x 15 grid with 0.1 m between points that turns with the robot's heading (base height minus 0.5 m minus the ground height, clamped to ±1 m). The student never gets them: student.py passes it the first 48 values and the depth image.
Terrain

The eight terrain types at level 6 of 10 (rough, stepped, blocks, stairs up, stairs down, slope up, slope down, gaps), each with the student's depth image.
Every environment has its own height map with 5 cm between samples, drawn at each reset from a pool shared by all environments: terrain/variants_per_type terrains (one by default) of each type in terrain/types, on each of 10 levels. The teacher's maps are 128 m wide, so that a robot cannot walk to their edge within an episode (an episode ends 1 m from the edge, without a reward); reaching the edge would cut its future rewards short. The student's maps are 32 m wide (student/terrain_size): its depth renderer keeps about 110 MB of RAM per 32 m terrain, so its 80 terrains take about 9 GB. The types are rough noise, stepped noise, blocks on rough ground, stairs up and down, rough slopes up and down, and gaps: flat rings separated by trenches 0.6 m deep.
Stairs, slopes and gaps are square rings around the flat 2 m platform where the robots spawn. At the top level, rough terrain spans about 0.4 m, terraces are 22 cm and stair risers 25 cm (treads 25-35 cm), blocks are up to 26 cm high, slopes rise 0.45 m per meter (the lowest friction, 0.5, caps them), and gaps are 30 cm wide. With 5 cm samples a stair riser is about 79 degrees steep instead of a ramp a policy can exploit.
Curriculum
Every environment keeps a level for each terrain type. The teacher starts all of them at level 0; the student, whose teacher walks every level already, starts them at random levels. After an episode, a robot that walked 4 m moves up a level on that type; one that ended less than half as far from its spawn point as its commands would have taken it (integrating the commanded velocity and turning rate, so that a robot told to walk in a circle is not expected to get far) moves down; one that passes the top level goes to a random level. So each kind of terrain gets harder only as the robot masters it: stairs climb their own levels instead of following the level a robot earned on easier terrain. With one level per robot for all kinds of terrain, the teachers did not learn to climb stairs at all: a robot promoted on easier terrain met stairs too high to climb and dropped back.
Teacher
It tracks forward commands of 1.0 to 3.6 m/s (with up to 0.6 m/s sideways and 1 rad/s turning), which start at half these ranges and approach them over training (command/initial_scale), with the legged_gym ANYmal C rough-terrain reward (penalties scaled by the 50 Hz control period; a step whose costs exceed its rewards counts a tenth of its sum). Above 1 m/s, the velocity error is measured relative to the commanded speed, and all costs count per commanded meter rather than per second, like a cost of transport. With legged_gym's fixed kernel and costs per second, the costs of running fast exceed what tracking earns, and a policy learns that standing still (earning the turning reward) pays more than walking somewhat slower than a fast command. Scaling the tracking reward up with the speed instead makes a fall cheap next to running fast: such a policy runs into high stairs and falls rather than slow down. Style costs on top of it give a natural, efficient trot:
- the mechanical power of the joints (Fu et al. 2021);
- hip abduction, hip flexion and knee angles away from the nominal stance;
- base height and tilt;
- foot slip;
- swing feet away from 10 cm above the ground they clear (the ground below, the far rim of a gap, or a step just ahead), weighted by their speed;
- the squared downward speed of the feet just before they touch down;
- a reward for one diagonal pair of feet carrying the robot.
All costs, the legged_gym penalties and the style costs alike, start at 20% of their weight and grow every iteration (gait/initial_cost_scale, as in Hwangbo et al. 2019), so that the robot first learns to walk at all. At full weight from the start, the costs of the exploring policy exceed anything walking could earn almost everywhere, standing still is its cheapest improvement, and training may never get past standing. Negative steps count a tenth of their sum rather than nothing (as legged_gym's only_positive_rewards would have it), so that the energy and style costs keep shaping the gait on terrain where they exceed the tracking reward. Trained with negative steps counting nothing and half the energy cost, a teacher walked at a cost of transport of 0.82 at 0.8 m/s, with a stretched stance, its front feet far ahead and its hind legs trailing: its costs exceeded the reward in a quarter of the steps, where they shaped nothing. Observation noise, random friction, pushes and an 80 Nm torque limit make the policy robust.
Student
The student's depth camera is the front camera of the ANYmal URDF, tilted 50 degrees down (20 more than its mount, depth/tilt) so that, standing on flat ground, every pixel sees the ground within the camera's 2 m range, from 0.54 m ahead of the base. VectorizedEnvironment::renderDepth() renders it for every environment at once on the GPU at 10 Hz (see Rendering sensors in a batch). A convolutional encoder reads the depth image, and a GRU remembers the terrain the camera saw before it passed under the robot. The student drives the robots while the teacher labels every visited state with its action (DAgger); for the first 300 iterations the teacher drives a shrinking share of the robots, so that the student first sees the states a good policy visits. During training the depth images get noise, holes and missing columns. Every 100 iterations student.py saves student_<N>.pt and records 10 s of the student driving alone, without noise, as student_<N>.mp4.
Checks
check.py recomputes what the environment reports from quantities it does not come from, and prints one line per check (exit status 1 if any fails):
- joint velocities, the angular velocity and the vertical base velocity from the change of joint positions, gravity direction and base height over one physics step;
- the distance each episode covered, from integrating the observed velocities;
- all 18 reward terms, the total (a tenth of it when negative) and the termination penalty;
- the statistics, the command timing, resets, terminations and the curriculum levels of every terrain type;
- the terrain types
terrain/typesselects, written as a YAML list either way; - the observation noise amplitudes, observation normalization, and the cost curriculum;
- the depth images, back-projected through the camera mounting in the URDF onto the scanned terrain heights;
- that runs with the same seed are identical on any number of threads.
It takes about 40 s. Without --teacher the robots only take random actions, so the checks that need a walking robot are skipped.
Results
The teacher trains at about 74,000 steps per second (1024 environments), 3000 iterations in about 36 minutes with its videos, in 12 GB of RAM. The student trains at about 35,000 steps per second (256 environments with depth images), 2000 iterations in about 9.5 minutes including its 21 videos, in 13.6 GB of RAM.
Walking straight on level 1, the student reaches 0.89, 1.43, 1.69 and 1.83 m/s when commanded 1.0, 2.0, 3.0 and 3.6 m/s, at a cost of transport of 0.37, 0.48, 0.58 and 0.62, and falls in 1-5% of its episodes; its teacher reaches 0.87, 1.59, 2.04 and 2.10 m/s.
student.py --mode test reports, per level and per kind of terrain, with the curriculum, noise and pushes off. Over all levels and the full command ranges, the teacher falls in 11% of its 20 s episodes and the student in 13% (on its 32 m terrains, where fast robots often reach the edge before 20 s). With the earlier, slower commands (0.5 to 1.8 m/s forward), the teacher falls in 9.5%. Falls per level, over all terrain types:
| Level | 0 | 1-4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|
| Teacher (terrain heights) | 0% | 2.7-5.4% | 14.9% | 8.7% | 13.8% | 24.7% | 31.8% |
| Student (depth images) | 0% | 3.5-7.1% | 12.9% | 12.9% | 21.8% | 26.4% | 30.6% |
Falls on the top level, from about 100 episodes per kind of terrain with every environment on it (--level 9):
| Level 9 | Rough | Stepped | Blocks | Stairs up | Stairs down | Slope up | Slope down | Gaps |
|---|---|---|---|---|---|---|---|---|
| Teacher | 0% | 26% | 28% | 51% | 27% | 13% | 6% | 90% |
| Student | 1% | 30% | 33% | 48% | 22% | 15% | 4% | 75% |
The 25 cm stairs and the gaps remain the hardest: on stairs up the robots stop after about a meter, and they step into most gaps (a 10 cm terrain scan for the teacher; a 5 cm scan made it hesitate at gaps and fall more elsewhere). The teacher climbs stairs up to level 4 (14 cm) and walks down to level 7 (21 cm) without falling.
Batching and resource sharing
A policy needs millions to billions of steps, and a desktop has a few dozen cores and one GPU. RaisimGymTorch keeps all of them busy by doing the work of all environments in a few large calls instead of many small ones, and by keeping one copy of everything the environments have in common.
Stepping environments in parallel
VectorizedEnvironment::step() distributes the environments over num_threads OpenMP threads. Each thread applies its environments' actions, integrates their Worlds for one control period, computes their rewards, resets those whose episode ended (adding the termination reward) and writes their observations into their rows of the shared array. step_and_observe() (in C++ stepAndObserve()) does stepping and observing in one parallel region, and then normalizes all observations with the running mean and variance that the module keeps. The Worlds are independent, so the threads never wait for each other within a step; only the slowest thread decides when the step ends.
- The arrays are allocated once by
RaisimGymVecEnvand written in place: nothing is copied or converted per environment, and Python never loops over environments. num_threadsabove the number of hardware threads minus one is reduced to it: the calling thread is busy with the policy and the GPU between steps, and a worker pool competing with it only adds latency.kStaticSchedule = truein an environment hands each thread a fixed block of environments (schedule(static)), which suits environments of equal cost; otherwise OpenMP balances them dynamically.- The runners call
configure_threads()(raisimGymTorch/env/openmp.py) before they import PyTorch; call it in your own scripts too. It binds the threads to cores (OMP_PROC_BIND) when the module uses GCC's OpenMP runtime (libgomp), as PyTorch does. A module built with Clang uses LLVM's runtime (libomp) beside PyTorch's libgomp, which binds the main thread to one core whenOMP_PROC_BINDis set, and libomp would then run every environment thread on that core; its threads stay unbound.VectorizedEnvironmentkeeps libomp's threads awake for 1 ms after each step (kmp_set_blocktime(), unlessKMP_BLOCKTIMEorOMP_WAIT_POLICYis set): libomp may otherwise put them to sleep at once, as it does on processors with performance and efficient cores, and waking them every step costs more than stepping small environments. With both, a Clang build trainsrsg_anymalwithin about 10% of a GCC build (0.073 against 0.066 s per iteration) instead of 9 times slower.
The teacher's rollout runs at 10,500 steps per second on one thread and at 107,000 on 19, ten times as fast; the processor has 8 performance cores and 12 slower efficient ones, so each thread beyond the eighth adds less. The student's rollout grows only 4.1 times, to 37,600 steps per second: its depth rendering (about 15 ms for 256 environments, every fifth step) and its network run on the GPU and do not get faster with more threads, and at 19 threads rendering takes about 45% of its rollout. Training adds the learning update to the rollout: the teacher trains at about 74,000 steps per second, and the student, which backpropagates through its GRU, at about 35,000.
The Python side batches its work the same way. The policy computes the actions of all environments in one forward pass on the GPU. The PPO in raisimGymTorch/algo/ppo samples the exploration noise in C++ (NormalSampler) and computes the generalized advantages of the whole rollout in one C++ call (compute_returns) instead of a Python loop over time steps. When the module is built with LibTorch (RAISIMGYM_TORCH_WITH_LIBTORCH, on by default), rsg_anymal and rsg_anymal_terrain run their evaluation rollouts in one C++ call (TorchPolicyRunner) with the policy exported to TorchScript.
Sharing resources between environments
Each environment owns a World and everything that changes during an episode, but the robot model and the terrain are the same in many environments. RaiSim's resources (see Shared resources across worlds) hold them once:
ArticulatedSystemResource::load()parses a URDF and prepares its collision meshes once; everyWorld::addArticulatedSystem(resource)creates a robot with its own state from it, so ANYmal's URDF is parsed and its collision meshes are convexified once, not once per environment. Its cameras share one table of per-pixel ray directions (74 KB for the student's 64 x 48 camera).HeightMapResourceholds the samples and collision tiles of a terrain, andWorld::addHeightMap(resource)creates a height map that only references them. A 128 m terrain with 5 cm samples holds 6.5 million heights;rsg_anymal_depth's pool of 80 such terrains exists once, not once per environment.
The environments hold their resources in function-local statics, so the first environment that asks creates a resource and the others receive it:
static ArticulatedSystemResource sharedRobot(const std::string& urdfPath) {
static std::mutex mutex;
static std::map<std::string, ArticulatedSystemResource> resources;
std::lock_guard<std::mutex> lock(mutex);
auto found = resources.find(urdfPath);
if (found == resources.end()) {
ArticulatedSystemOption options;
options.convexifyCollisionMeshes = true;
found = resources.emplace(urdfPath, ArticulatedSystemResource::load(urdfPath, "", {}, options)).first;
}
return found->second;
}
anymal_ = world_->addArticulatedSystem(sharedRobot(resourceDir_ + "/anymal/urdf/anymal.urdf"));Switching terrain is then cheap: rsg_anymal_depth swaps a robot's height map at every reset by removing it from the World and adding another pool terrain, which copies no heights or collision tiles. A terrain shared this way must be generated from the configuration and an index alone (as both terrain environments do), so that every environment derives the same one.
Rendering sensors in a batch
Rendered one camera at a time, depth images cost more than the physics: in rayrai's benchmark, the 80 x 60 depth cameras of 256 environments take 27.4 ms per step with one RayraiWindow per environment, and 3.24 ms with the batch renderer described here. An environment that defines
std::vector<raisim::DepthCamera*> depthCameras();gets render_depth() in Python, which returns the images of all environments as one [num_envs, cameras, height, width] array of depths in meters (0 where nothing was hit). VectorizedEnvironment::renderDepth() drives rayrai's SensorBatchRenderer in an OpenGL context of its own:
- The OpenMP threads capture every World in parallel: the poses of its objects and cameras, without OpenGL.
- One render pass draws every camera into its own tile of one render target. Each camera skips the meshes outside its view, and the height maps are cut into chunks of 32 x 32 cells, so a camera draws only the terrain in front of it.
- One read per column of tiles copies all images back, into the array that Python receives.
The renderer shares as the physics does: it loads each mesh file once, and height maps with equal heights, such as the copies of one HeightMapResource, share one set of chunk meshes across all Worlds, so the terrain memory grows with the number of distinct terrains rather than with the number of environments, and a reset onto a terrain seen before builds nothing. The call releases Python's global interpreter lock while it renders.
For the student's 256 environments, with 64 x 48 cameras on 32 m terrains, render_depth() and the copy of its images to the GPU take about 15 ms. The student renders only every fifth control step (10 Hz, student/depth_every_n), which cuts that cost to a fifth. Sharing the terrain meshes matters as much as batching the draws: before the renderer shared and chunked them, every World kept meshes of its own terrain, and DAgger training of an earlier configuration of rsg_anymal_depth (16 m terrains) ran 1024 environments at 9.7k steps per second in 42.7 GB of RAM, while 2048 ran out of memory. With shared, chunked meshes, the same training ran 1024 environments at 70k steps per second in 5.8 GB, and 2048 in 6.4 GB.
Evaluation videos
With record_video: True (the default), the runners record the first environment during their evaluations as policy_<N>.mp4 (student_<N>.mp4 for the depth student) next to the checkpoint. The training process renders the video itself with rayrai, so no viewer has to be connected: a desktop session works, and so does a headless machine whose GPU driver provides EGL. The camera follows the first robot and the video plays in real time (30 frames per second of simulated time). In an environment with depth cameras, every frame also shows the first camera's depth image in its top-right corner, near bright and missing or beyond the far plane black. The runner prints the saved path, or why the rollout was not recorded (no OpenGL context or no ffmpeg).
With render: True in cfg.yaml, the first environment also runs a RaisimServer; connect rayrai_tcp_viewer as described in Visualization to watch it, and the evaluations then run in real time. Older RaisimUnity/Unreal visualization workflows have been replaced; see Legacy Integrations for migration notes.
Scaling up
Hard tasks need far more experience than these examples. About 160 billion time steps trained the controller above, at about 500,000 steps per second in its environment on a Ryzen 9 3950X, with an actuator network that cost as much as the physics simulation.
Writing an environment
Copy an environment directory under raisimGymTorch/raisimGymTorch/env/envs (rsg_anymal is the smallest), rename it, change the module its scripts import (from raisimGymTorch.env.bin import rsg_anymal) to the new name, and rebuild with pip install -e . --no-build-isolation; each directory becomes a module of its name. The class in Environment.hpp derives from RaisimGymEnv and implements:
| Method | Does |
|---|---|
| constructor | creates world_, adds objects, sets obDim_ and actionDim_, and the reward terms (rewards_.initializeFromConfigurationFile(cfg["reward"])) |
init() | runs once after construction |
reset() | starts an episode |
step(action) | applies an action, integrates the World for one control period, records the rewards and returns their sum |
observe(ob) | writes the observation |
isTerminalState(terminalReward) | ends the episode, with a terminal reward |
and optionally:
| Member | Does |
|---|---|
curriculumUpdate() | called by curriculum_callback(), once per training iteration in the runners |
setSeed(seed) | seeds the environment's random generators (environment i gets seed + i) |
observeCritic(ob), criticObDim_ | a separate observation for the value function |
depthCameras() | the depth cameras that render_depth() renders |
statisticNames(), statistics(values) | values to log per environment, such as a curriculum level, returned by get_statistics() |
kStaticSchedule | true for a fixed assignment of environments to threads |
kParallelizeVisualEnvironment | true when the first environment, which runs the RaisimServer with render: True, may step in parallel with the others (its physics steps lock the server's mutex) |
The Python class of the module is named by the ENVIRONMENT_NAME macro in raisim_gym.cpp (RaisimGymEnv by default). To keep several copies of RaisimGymTorch side by side, change the package name in setup.py (name='raisim_gym_torch') or use separate Python environments. Delete the build and raisim_gym_torch.egg-info directories before a clean rebuild when you change Python interpreters or build configurations.
To use another network, change build_actor_network() and build_critic_network() in runner.py, and build_evaluation_network() if it needs a special evaluation wrapper; no C++ changes are needed.
Sensor noise seeds
Each vectorized environment assigns a distinct World sensor seed after init() and before the initial reset(): environment index i uses i + 1. VectorizedEnvironment::setSeed(seed) calls the user setSeed(seed + i) hook and then assigns World seed uint64_t(uint32_t(seed)) + i + 1. This works even when the derived hook does not call the base implementation. Seed assignment is independent of OpenMP scheduling, so cloned runs with the same environment order replay their streams. Negative user seeds use their unsigned 32-bit representation for the World seed; ranges whose final user seed exceeds INT_MAX are rejected before invoking any hooks.
Reseeding restarts sensor random streams. It preserves delivered measurements, IMU filters and bias, and pending samples. When an episode should also restart the IMU model, call imu->reset() from the environment's reset() implementation.
Debugging
A nanobind module is written in C++ but does not run as an executable of its own, which makes it hard to debug. RaisimGymTorch builds a debug app that wraps an environment in an executable when you build in the Debug configuration:
python setup.py build_ext --inplace --DebugThe executable is created next to the module (raisimGymTorch/raisimGymTorch/env/bin). Run it as
./<environment name>_debug_app <full path to rsc directory> <full path to the cfg file>or open the raisimGymTorch directory in CLion, which adds the debug app as a run configuration. On Windows, link against the Debug build of RaiSim: executables built with Visual Studio do not work with a library built with different runtime flags.
Common issues
- If Python scripts complain about a missing
libcudnn.so, install cuDNN, for example withconda install -c nvidia cudnn. render_depth()needs a rayrai withSensorBatchRenderer, which needs desktop OpenGL 3.3 (4.1 on macOS).- Video recording in
rayrai_tcp_viewerusesffmpegfromPATH(or$RAYRAI_FFMPEG); without it, the viewer writes a PNG sequence. - Two RaisimGymTorch environment modules cannot be imported into one Python process.
- A training script that sets
OMP_PROC_BINDitself, instead of callingconfigure_threads(), runs every environment thread of a Clang-built module on one core:rsg_anymalthen takes 0.58 s per iteration instead of 0.07 s (see Stepping environments in parallel).