TorchRL
TorchRL is a PyTorch-native toolkit for reinforcement learning, decision making,
robotics, and simulation. It is not a single algorithm implementation or a
narrow benchmark suite: it is a collection of composable pieces for building RL
systems while keeping the code close to the PyTorch programming model. Recent
work has made this especially strong for recurrent RL, MuJoCo-based control,
multi-agent training, replay-buffer and collector infrastructure, and reusable
loss/value-estimation components.
The library is built around three ideas:
- Data should have names, structure, batch dimensions, and devices all the way
through the training loop.
- Environments, policies, replay buffers, objectives, and collectors should be
independent modules that can be swapped without rewriting the rest of the
stack.
- Research code should scale from a local prototype to vectorized,
multiprocess, distributed, compiled, recurrent, multi-agent, model-based, or
offline workflows without changing the data model.
That common data model is TensorDict,
a dictionary-like tensor container with PyTorch operations, device transfers,
shared-memory support, memmaps, lazy views, and nn.Module wrappers.
Getting started |
API reference |
Tutorials |
Knowledge base |
Examples |
SOTA implementations
What's new in TorchRL 0.15
TorchRL 0.15 introduces powerful new capabilities for robot learning, offline
RL, data interoperability, and training at scale.
- Robotics and deployment. Use MuJoCo Menagerie and MicroDuck environments,
compose low-level controllers, and export TensorDict policies to ONNX.
Menagerie example ·
Low-level control tutorial
- Model-based and offline RL. TD-MPC2, Flow Q-Learning, and Transitive RL
provide components and training implementations for control and offline RL.
TD-MPC2 ·
FQL ·
Transitive RL
- PyTorch and dataset interoperability. Use
buffer.as_dataset() with a
PyTorch DataLoader, or buffer.export(...) to exchange trajectory data
with LeRobot and Hugging Face Datasets.
PyTorch data integration ·
LeRobot tutorial
- Data collection. Use
replay_write_mode="trajectory" to write complete
episodes to replay, with new readiness and policy-version controls.
Collectors and execution models
- Evaluation and checkpointing. Evaluate across environments, schedule
evaluation during training, and resume supported recipes from checkpoints.
Evaluation ·
Checkpointing
- Sequence models and RLHF. Build Transformer-based policies and train
reward models from preference data.
Transformer example ·
Reward-model recipe
A quick mental model
TorchRL represents an RL interaction as a TensorDict that moves through a small
number of reusable components:
TensorDict
-> policy module writes actions and log-probs
-> environment reads actions and writes next observations, rewards, done flags
-> collector batches trajectories from one or many workers
-> replay buffer stores, samples, prioritizes, and transforms data
-> loss module reads named keys and writes differentiable losses
-> optimizer updates ordinary PyTorch parameters
The same object can carry observations, pixels, actions, rewards, masks,
recurrent states, agent groups, sampled indices, priorities, or custom task
fields. The result is less glue code and fewer hidden assumptions about
what each algorithm or environment returns.
Quick demo
A local rollout is just a TensorDict passed between a PyTorch module and an
environment:
import torch
from tensordict.nn import TensorDictModule
from torch import nn
from torchrl.envs import PendulumEnv, StepCounter, TransformedEnv
# A PyTorch-native environment with an ordinary transform stack.
env = TransformedEnv(PendulumEnv(), StepCounter(max_steps=200))
# Policies are regular nn.Modules wrapped with explicit TensorDict keys.
policy = TensorDictModule(
nn.Sequential(
nn.LazyLinear(64),
nn.Tanh(),
nn.Linear(64, 1),
nn.Tanh(),
),
in_keys=["observation"],
out_keys=["action"],
)
rollout = env.rollout(max_steps=32, policy=policy)
assert rollout.batch_size == torch.Size([32])
assert rollout["next", "reward"].shape[:1] == torch.Size([32])
Nothing in this pattern is specific to Pendulum. The same keys-and-TensorDict
interface is used by batched environments, multi-agent tasks, collectors,
replay buffers, recurrent modules, transforms, and losses.
What TorchRL is today
TensorDict-first pipelines
RL code tends to accumulate special cases: tuples from one environment, dicts
from another, separate arrays for recurrent states, masks next to data rather
than inside it, and losses that silently assume a particular batch layout.
TorchRL uses TensorDict to make those assumptions explicit.
TensorDict supports common tensor operations while preserving named fields:
# These operations preserve the structure and operate on every compatible value.
batch = torch.stack(list_of_tensordicts, dim=0)
batch = batch.reshape(-1)
batch = batch.to("cuda")
mini_batch = batch[:128]
# Nested keys make multi-agent, recurrent, and next-state data explicit.
reward = batch["next", "reward"]
agent_obs = batch["agents", "observation"]
hidden = batch["recurrent_state", "h"]
This is the reason TorchRL components compose: a collector can emit a TensorDict,
a replay buffer can store it without losing structure, a transform can add or
remove keys, and a loss can read exactly the keys it needs.
Environments and transforms
TorchRL includes native environments, wrappers for popular environment libraries,
and vectorized containers for running many environments at once. The environment
API exposes specs for observations, actions, rewards, and done flags, so policies
and transforms can check shapes, devices, dtypes, and bounds before a training
job runs for hours.
Environment support includes:
- PyTorch-native environments such as
PendulumEnv, and custom MuJoCo tasks
built on MujocoEnv.
- Wrappers for Gymnasium, Gym, DM Control, Brax, Jumanji, PettingZoo, VMAS,
OpenSpiel, Safety-Gymnasium, Isaac Lab, and other optional libraries.
SerialEnv, ParallelEnv, and batched wrappers for local vectorization and
multiprocessing.
- Environment transforms for observation normalization, image conversion,
reward transforms, action masking, action scaling (
ActionScaling), action
flattening (FlattenAction), auto-reset, frame stacking, state reconstruction,
and more.
Transforms are first-class TorchRL modules. They can run on-device, participate
in specs, and be inserted, removed, or composed without wrapping the whole
environment in opaque adapter layers.
Macro-control primitives expand
high-level commands into sequences of low-level actions.
from torchrl.envs import Compose, DoubleToFloat, ObservationNorm, TransformedEnv
from torchrl.envs.libs.gym import GymEnv
base_env = GymEnv("HalfCheetah-v4", device="cuda:0")
env = TransformedEnv(
base_env,
Compose(
ObservationNorm(in_keys=["observation"]),
DoubleToFloat(),
),
)
Collectors and execution models
Collectors are the bridge between policies and environments. A collector owns
the execution loop, batches trajectories, handles devices, and can update policy
weights while environments keep running.
TorchRL includes single-process, async, multiprocess, and distributed
collectors. This lets the same policy and loss code be used across small smoke
tests, GPU-heavy simulation, CPU environment farms, or asynchronous evaluation
setups.
from torchrl.collectors import Collector
collector = Collector(
create_env_fn=env,
policy=policy,
frames_per_batch=1024,
total_frames=1_000_000,
)
for data in collector:
# data is a TensorDict with time, environment, and key structure preserved.
train_step(data)
For larger jobs, the collector family adds async execution, multiple worker
processes, weight updaters, evaluator loops, profiling hooks, and fake-data
helpers for testing downstream code without stepping an expensive environment.
TorchRL 0.14 made it easier to scale data collection across local processes and
distributed workers through a shared Collector API. For example, if make_env
creates an environment, use multiple local processes with:
multi_collector = Collector(
make_env, policy, num_collectors=4, sync=True, frames_per_batch=1024
)
Here sync=True waits for all four workers. This call returns a
MultiSyncCollector, the implementation that manages synchronous worker
processes.
The same Collector API supports several execution modes:
- Single process:
Collector(make_env, policy, ...) collects in the current
process.
- Synchronous workers:
num_collectors=4, sync=True collects across four
local workers and waits for each when forming a batch.
- Asynchronous workers:
num_collectors=4, sync=False receives data as
workers finish.
- Distributed workers:
backend="ray", "rpc", or "distributed" selects
a distributed execution backend.
For asynchronous environment stepping and batched policy inference,
AsyncBatchedCollector combines an AsyncEnvPool, which runs environments
independently, with an inference server that groups their policy requests:
from torchrl.collectors import AsyncBatchedCollector
collector = AsyncBatchedCollector(
[make_env] * 4, policy=policy, frames_per_batch=1024, env_backend="threading"
)
The async collector can also write to replay in the background. In 0.15,
replay_write_mode="trajectory" writes complete episodes to replay,
buffer.sample(wait=True) waits for sampleable data on supported buffers, and
multi_collector.worker_policy_versions() reports each worker's policy version
when track_policy_version=True.
See collector APIs,
distributed collectors,
async environments, and
collectors and replay.
Replay buffers and offline data
TorchRL replay buffers are modular: storage, sampler, writer, collate function,
transforms, prefetching, priority updates, and device movement are separate
pieces. That makes it possible to use the same interface for simple in-memory
replay, memmap-backed storage, prioritized replay, CUDA-aware sampling, offline
datasets, or custom storage layouts. HERReplayBuffer relabels goals for
goal-conditioned RL. For compact observations, NextObservationDelta and
NextStateReconstructor support reconstruction when sampling from replay.
from torchrl.data import LazyMemmapStorage, TensorDictPrioritizedReplayBuffer
buffer = TensorDictPrioritizedReplayBuffer(
storage=LazyMemmapStorage(1_000_000),
alpha=0.7,
beta=0.5,
batch_size=256,
prefetch=2,
)
buffer.extend(collector_batch)
sample = buffer.sample()