Skip to content

Using ruxla from PyTorch

ruxla.VecEnv steps environments as native code on CPU threads and exchanges NumPy arrays, so a PyTorch agent can use it like any CPU vector environment: the environments stay on the CPU, the agent runs on the GPU, and only observations, rewards, and actions cross between them. Environments written in JAX (imported and compiled ahead of time) run this way without JAX at run time.

The example python/examples/ppo_torch.py is a single-file PPO in the style of CleanRL that does all of this.

Installation

Install PyTorch for your platform (pytorch.org) and ruxla (pip install ruxla, Installation). ruxla.VecEnv needs neither JAX nor a GPU for the environments. From a clone of the repository:

python python/examples/ppo_torch.py Breakout-MinAtar --num-envs 64            # agent on the GPU
python python/examples/ppo_torch.py CartPole-v1 --device cpu --total-steps 2e5
python python/examples/ppo_torch.py Breakout-MinAtar --num-envs 64 --compile  # LeanRL-style agent

The environment is a name of ruxla.VecEnv (CartPole-v1, Breakout-MinAtar, ..., or the module name of an imported environment in an extension built with jax-envs), or a module of a library built by ruxla.compile_env with --library <path>. --num-envs, --threads, --total-steps, and --seed set the batch, the threads that step the environments, the length of the run, and the seed.

The stepping loop

VecEnv.step_into writes the results into arrays you allocate once. With pinned (page-locked) PyTorch tensors as those arrays, the copies to the GPU are asynchronous, and nothing is allocated per step:

import numpy as np, torch, ruxla

n, device = 64, torch.device("cuda")
envs = ruxla.VecEnv("Breakout-MinAtar", n, seed=0, num_threads=8)
obs_dim = int(np.prod(envs.obs_shape))

# Host buffers, pinned, and NumPy views of the same memory for ruxla to write into.
obs_host = torch.zeros((n, obs_dim), pin_memory=True)
rew_host = torch.zeros(n, pin_memory=True)
term_host = torch.zeros(n, dtype=torch.bool, pin_memory=True)
trunc_host = torch.zeros(n, dtype=torch.bool, pin_memory=True)
act_host = torch.zeros(n, dtype=torch.int32, pin_memory=True)
obs_np, rew_np, term_np, trunc_np, act_np = (
    t.numpy() for t in (obs_host, rew_host, term_host, trunc_host, act_host)
)

obs = torch.from_numpy(envs.reset().reshape(n, obs_dim)).to(device)
for t in range(num_steps):
    action = policy(obs)                      # on the GPU
    act_host.copy_(action)                    # waits for the GPU: the environments need the actions
    envs.step_into(act_np, obs_np, rew_np, term_np, trunc_np)
    obs = obs_host.to(device, non_blocking=True)
    reward = rew_host.to(device, non_blocking=True)
    done = (term_host.to(device, non_blocking=True) | trunc_host.to(device, non_blocking=True)).float()
    ...                                       # store the transition, accumulate statistics on the GPU
  • One synchronization per step. Copying the actions to the host waits for the GPU, which also guarantees that the previous step's asynchronous copies out of the host buffers are done before step_into overwrites them. Keep episode statistics (returns, counts) in GPU tensors and read them once per update or log; a float(tensor) or .item() every step adds a second synchronization.
  • No final observations. step_into does not compute the observation that ended an episode (the automatic reset replaces it in obs), so truncated episodes are not bootstrapped, as in CleanRL's ppo.py. Use step, which returns info["final_observation"], if your algorithm needs it.
  • The GIL. step_into releases the GIL while the threads step, so other Python threads can run.

Threads

The threads of VecEnv (num_threads, or --threads in the example) step contiguous chunks of the environments, the calling thread included; by default, one per physical core and at most one per 32 environments. With the agent on the GPU, give the environments the cores that the process has; with --device cpu, the agent's own PyTorch threads compete for the same cores, so leave some to it (torch.set_num_threads). NumPy's OpenBLAS threads can also take CPU time from the workers; set OPENBLAS_NUM_THREADS=1 when timing.

A compiled agent (--compile)

With a few dozen environments, a step of the environments takes well under a millisecond, and the agent's Python and kernel-launch overhead dominates the loop. --compile runs the agent as LeanRL does:

  • the policy of each step under torch.compile(policy, mode="reduce-overhead", fullgraph=True), which replays it as a CUDA graph; torch.compiler.cudagraph_mark_step_begin() before each call, and the outputs cloned, since the next replay overwrites them;
  • actions sampled with the Gumbel-max trick (argmax(logits - log(-log(u))), the same distribution as a categorical sample), which compiles into the graph;
  • the PPO loss compiled, and Adam with fused=True.

The first updates are slower while PyTorch compiles. On the CPU (--device cpu), --compile compiles without CUDA graphs.

When it pays off

The gain comes from stepping the environments faster on the CPU than JAX does, at batch sizes where the GPU is underused. With the compiled agent on an RTX 5090 and 16 cores, environments imported from JAX raise PPO training throughput over the best of four JAX backends (CPU or GPU, with or without an optimistic reset) by 1.4 to 5.8 times on eight of nine tasks at 8 and 64 environments, and by 3.2 to 5.8 times on Craftax Classic and Craftax (Benchmarks).

It pays off with:

  • small batches, typically 8 to 64 environments, as in evaluation, search, distributed actors, or a single-GPU agent that trains on a few dozen environments;
  • environments with expensive, rarely taken branches, such as procedurally generated levels (Craftax), where native code builds a new level only when an episode ends.

It does not with:

  • very large batches (thousands of environments), where the GPU steps the batch faster than the CPU and copying large observations to the GPU adds up: at 1,024 environments the gain falls to 1.0–1.5 times and turns into a loss on Go 9×9 and Craftax;
  • environments whose JAX step is cheap on the GPU, or whose imported step is expensive (Gardner chess computes its legal moves densely and loses at every batch);
  • agents written in JAX: a training loop fused into one jax.jit on the GPU stays faster than any host loop.

Choosing CPU or GPU discusses the trade-off for environments alone.