Rust learner

A port of the PPO learner to Rust and libtorch, run side by side with the Python one.

7 min read

crates/learner (the physlab-learn binary) is a port of the Python learner (python/physlab_rl) to Rust, using tch-rs bindings to libtorch. It is an experiment: the Python learner stays the one we train with until the Rust one has matched it on both speed and results. Both run on the same environment crate (crates/rlenv); the Rust learner calls it directly instead of through the Python binding.

Running it#

text
just learner-setup                                     # downloads libtorch and CUDA tools into .tools/ (once)
just learn tasks/ground-touch-v1.json --total-steps 20_000_000
just learn-eval runs/<id>/final.safetensors
just learn-compare runs/<id-a> runs/<id-b>             # or a directory of runs
just learn-ab tasks/ground-touch-v1.json 20_000_000 "1 2 3"

just learn takes the same options as just train, with the same single-agent defaults. The learn* recipes build with the release-lto profile (the one the Python extension uses) and put libtorch's libraries on PATH. The learner crates are left out of the workspace-wide just lint / just test (CI has no libtorch or CUDA tools) and have their own just learner-lint and just learner-test.

Side by side#

Both learners write the same run directory (manifest.json, metrics.jsonl, summary.json) with the same metric keys, so the Python tools and the charts read either. Rust run ids end in -rs (-candle, -burn for the other frameworks), and their manifests say "learner": "rust-tch" (rust-candle, rust-burn) under environment.

Rust checkpoints are .safetensors files: the weights under the Python model's parameter names, plus the rest of the checkpoint as JSON metadata. The Python tools load them directly:

text
uv run python -m physlab_rl.evaluate runs/<rust-run>/final.safetensors
uv run python -m physlab_rl.rust_checkpoint export runs/<python-run>/final.pt out.safetensors
just learn-eval out.safetensors

Evaluation is deterministic (held-out seeds, argmax actions), so a checkpoint scores the same in either learner.

just learn-ab trains the same task and seeds with both learners, each with its default options, and prints physlab-learn compare's table: steady-state steps/s and the per-phase times (env, inference, update) of each run, then final success and steps to 80 % per learner.

Results#

Ground touch, 20M steps, seeds 1–3, runs/ab/cool-20261017-131912:

LearnerSteps/sEnv sInference sUpdate sFinal success
Python, defaults687 k0.0780.0330.0793/3 at 1.00
Python, --cuda-graphs --pipeline-rollout770 k0.0210.0760.0683/3 at 1.00
Rust, defaults (CUDA graphs, pipelined rollout)805 k0.0280.0650.0683/3 at 1.00

The times are per update cycle; with a pipelined rollout, "env" is only the time spent waiting for env steps. With CUDA graphs the update takes the same time in both; the Rust rollout is a little faster than Python's pipelined one. Both learners reached 80 % evaluation success between 2.6M and 5.2M steps (evaluations every 1.3M).

Run the learners one after another with a minute's pause in between: right after a run the CPU is still hot and boosts less, which slowed the next run by up to 10 %.

candle and burn#

The tch learner needs a little C++ of our own for what tch doesn't bind. To see what the pure-Rust frameworks cost, the same single-agent learner also runs on candle (crates/learner-candle, just learn-candle) and burn (crates/learner-burn, just learn-burn, CUDA through CubeCL with kernel fusion). Everything but the tensor work is shared with tch in crates/learner-core: envs, the pipelined rollout, normalisers, evaluation, run directories and the training loop, so only the model, the action step and the PPO update differ. Each uses its framework's own autograd and Adam; GAE and the update's statistics are computed on the CPU. Their checkpoints use the same format, so just learn-eval and the Python tools load them.

just learn-frameworks trains a task with all three, a minute apart, and compares them. Ground touch, 20M steps, seeds 1–3, runs/frameworks/20261017-155127:

LearnerSteps/sWhole runInference sUpdate sFinal success
tch842 k817 k0.0580.0653/3 at 1.00
burn455 k165 k0.1230.1633/3 at 1.00
candle349 k344 k0.0490.2893/3 at 1.00

"Steps/s" is the steady-state median per update; "whole run" is total steps over wall time. All three reached 80 % evaluation success between 2.6M and 3.9M steps.

  • burn is about half as fast as tch once running, but compiles and tunes its GPU kernels at run time: the first updates and every new shape (such as the first evaluation) take seconds, so a 20M-step run spends more than half its time on that. Inference is slower than tch's (per-call overhead), the update about 2.5× slower.

  • candle has the fastest inference but the slowest update: its autograd allocates and adds a fresh gradient for every operation and fuses nothing, so the backward pass dominates (4.5× tch's update).

  • Neither removes native code from the build. candle compiles its CUDA kernels with NVIDIA's compiler when it builds, which needs the CUDA toolkit and MSVC (just learner-setup downloads the toolkit parts); burn needs no toolkit to build but loads CUDA's math library when it compiles kernels at run time. candle and burn can't be built in one cargo command, as they need conflicting modes of the CUDA bindings they share.

  • Not ported to either: --init-checkpoint, --amp, CUDA graphs and the optimizer state in checkpoints.

What is ported#

PartStatus
Single-agent PPO: GAE, truncation bootstrap, return scaling, observation normalisation, clipped value loss, target KL, annealed learning ratePorted
Fused Adam, TF32 matmulsPorted, on by default on CUDA (--no-fused-adam, --no-tf32) as in Python
Pipelined rolloutPorted, on by default on CUDA (--no-pipeline-rollout); off by default in Python for single-agent tasks
CUDA graphs of the updatePorted, on by default on CUDA (--no-cuda-graphs); off by default in Python for single-agent tasks
--cpu-placement (hybrid CPUs on Windows)Ported, fast by default as in Python
--amp bf16Ported (trunks in bf16, heads and losses in fp32)
Held-out evaluation, checkpoints, --init-checkpoint, run manifest and metricsPorted
Match tasks: self-play, opponent pool, ratings, RLGym bots, drills, kickstartingNot yet
Auxiliary tasks (reward prediction, state representation)Not yet
CUDA graphs of the rollout's action step (--cuda-graph-act), overlapped update, pinned stagingNot yet
--resume, save/stop control, OpenTelemetry metrics and traces, system load samplingNot yet

How it differs inside#

  • One flat parameter tensor. Every weight and bias is a tensor over a slice of one flat tensor, and its gradient over the same slice of one flat gradient buffer. Backward adds every gradient into that buffer in place, so zeroing, gradient clipping and the fused Adam step are one or a few kernels however deep the network is.

  • Adam's step count and learning rate live on the GPU. Nothing in the update waits for the CPU, so each minibatch step (forward, backward, clip, Adam) can be captured as a CUDA graph and replayed as one launch. As in Python there is one graph per minibatch size, captured on first use. Unlike Python's, minibatches are not padded: every row of a single-agent rollout is valid, so a graphed update computes exactly what the eager one does.

  • The pipelined rollout splits the envs into two halves and steps one on a worker thread while the main thread computes the other's actions. Every row's trajectory is the serial rollout's for the same actions; only the order of the sampling draws changes. Rust has no interpreter lock to hand over, so the worker never waits on the main thread.

  • Patched bindings. The published tch release doesn't build on Windows against the libtorch it targets, and doesn't bind fused Adam, setting a tensor's .grad, the TF32 switch, CUDA graphs or streams. Its torch-sys crate is vendored with fixes and small C wrappers (vendor/torch-sys/PATCHES.md). The CUDA graph calls are a small C++ file of the learner (crates/learner/csrc/cuda_graph.h), called through the cxx crate and built against NVIDIA's CUDA runtime headers. Both are called from one module, crates/learner/src/ffi.rs, where each unsafe block is marked with its reason.

Plans#

  1. Match tasks. Self-play, the opponent pool, ratings and evaluation against the RLGym bots, which tch can run (they are TorchScript files).

  2. Overlapped update. Training on one rollout while collecting the next, as Python's --overlap-update.