rl
A modular, primitive-first, python-first PyTorch library for Reinforcement Learning.
Top Related Projects
A toolkit for developing and comparing reinforcement learning algorithms.
TensorFlow Reinforcement Learning
Ray is an AI compute engine. Ray consists of a core distributed runtime and a set of AI Libraries for accelerating ML workloads.
OpenAI Baselines: high-quality implementations of reinforcement learning algorithms
Dopamine is a research framework for fast prototyping of reinforcement learning algorithms.
Quick Overview
The pytorch/rl repository is a collection of reinforcement learning (RL) algorithms and environments implemented using the PyTorch deep learning framework. It provides a set of tools and examples for researchers and practitioners to explore and experiment with various RL techniques.
Pros
- Diverse Algorithms: The repository includes implementations of several popular RL algorithms, such as DQN, PPO, and A2C, allowing users to compare and experiment with different approaches.
- PyTorch Integration: By using PyTorch, the project benefits from the library's powerful and flexible deep learning capabilities, making it easier to integrate RL models with other deep learning components.
- Customizable Environments: The project includes a variety of OpenAI Gym-compatible environments, which can be used to test and evaluate RL algorithms.
- Active Development: The project is actively maintained, with regular updates and contributions from the PyTorch community.
Cons
- Limited Documentation: The project's documentation could be more comprehensive, making it challenging for newcomers to get started and understand the codebase.
- Steep Learning Curve: Reinforcement learning, in general, can have a steep learning curve, and this project may not be the most beginner-friendly for those new to the field.
- Potential Compatibility Issues: As the project is built on PyTorch, users may encounter compatibility issues when using different versions of PyTorch or other dependencies.
- Narrow Focus: The project is primarily focused on RL algorithms and environments, and may not provide a comprehensive set of tools for other aspects of the RL workflow, such as hyperparameter tuning or visualization.
Code Examples
Here are a few code examples from the pytorch/rl repository:
- Training a DQN Agent:
import gym
from rl.agents.dqn import DQNAgent
from rl.environments import make_env
env = make_env('CartPole-v0')
agent = DQNAgent(env.observation_space.shape, env.action_space.n)
for episode in range(1000):
state = env.reset()
done = False
while not done:
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
agent.step(state, action, reward, next_state, done)
state = next_state
This code sets up a DQN agent to train on the CartPole-v0 environment.
- Training a PPO Agent:
import gym
from rl.agents.ppo import PPOAgent
from rl.environments import make_env
env = make_env('LunarLander-v2')
agent = PPOAgent(env.observation_space.shape, env.action_space.n)
for episode in range(1000):
state = env.reset()
done = False
while not done:
action, log_prob = agent.act(state)
next_state, reward, done, _ = env.step(action)
agent.step(state, action, reward, next_state, done, log_prob)
state = next_state
agent.update()
This code sets up a PPO agent to train on the LunarLander-v2 environment.
- Evaluating an A2C Agent:
import gym
from rl.agents.a2c import A2CAgent
from rl.environments import make_env
env = make_env('Pendulum-v0')
agent = A2CAgent(env.observation_space.shape, env.action_space.shape)
state = env.reset()
done = False
while not done:
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
state = next_state
This code sets up an A2C agent to evaluate on the Pendulum-v0 environment.
Getting Started
To get started with the pytorch/rl repository, follow these steps:
- Clone the repository:
git clone https://github.com/pytorch/rl.git
- Install the required dependencies:
cd rl
pip
Competitor Comparisons
A toolkit for developing and comparing reinforcement learning algorithms.
Pros of OpenAI Gym
- Provides a wide range of environments for reinforcement learning, including classic control problems, Atari games, and robotics simulations.
- Offers a standardized interface for interacting with these environments, making it easier to develop and test reinforcement learning algorithms.
- Supports multiple programming languages, including Python, C++, and Lua, allowing for flexibility in the choice of implementation.
Cons of OpenAI Gym
- The environment setup and configuration can be complex, especially for more advanced simulations.
- The documentation, while generally good, may not always be comprehensive or up-to-date, making it challenging for beginners to get started.
- The performance of the simulations can be limited, especially for more complex environments, which may impact the training process.
Code Comparison
Here's a brief code comparison between PyTorch RL and OpenAI Gym:
PyTorch RL (creating a simple policy network):
import torch.nn as nn
class PolicyNetwork(nn.Module):
def __init__(self, state_size, action_size):
super(PolicyNetwork, self).__init__()
self.fc1 = nn.Linear(state_size, 64)
self.fc2 = nn.Linear(64, action_size)
def forward(self, state):
x = self.fc1(state)
x = nn.ReLU()(x)
x = self.fc2(x)
return x
OpenAI Gym (creating a simple environment and running an agent):
import gym
env = gym.make('CartPole-v0')
observation = env.reset()
for _ in range(1000):
env.render()
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
if done:
observation = env.reset()
TensorFlow Reinforcement Learning
Pros of TRFL
- TRFL provides a set of building blocks for constructing reinforcement learning agents, making it easier to experiment with different algorithms and architectures.
- The library includes a wide range of reinforcement learning algorithms, including DQN, A3C, and PPO, among others.
- TRFL is well-documented and includes examples and tutorials to help users get started.
Cons of TRFL
- TRFL is primarily focused on TensorFlow, which may not be the preferred framework for some users.
- The library can be more complex to set up and use compared to PyTorch/RL, which has a more user-friendly interface.
- TRFL may not have the same level of community support and contributions as PyTorch/RL.
Code Comparison
PyTorch/RL:
import torch.nn as nn
class DQN(nn.Module):
def __init__(self, state_size, action_size):
super(DQN, self).__init__()
self.fc1 = nn.Linear(state_size, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, action_size)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.fc3(x)
TRFL:
import trfl
def dqn_loss(q_values, actions, rewards, next_q_values, terminals, discount):
q_selected = trfl.gather_along_first_axis(q_values, actions)
target_q_values = rewards + (1.0 - terminals) * discount * trfl.maximum_along_first_axis(next_q_values)[0]
return trfl.mean_squared_error(q_selected, target_q_values)
Ray is an AI compute engine. Ray consists of a core distributed runtime and a set of AI Libraries for accelerating ML workloads.
Pros of Ray
- Ray provides a more comprehensive set of tools for distributed computing, including support for distributed training, hyperparameter tuning, and serving of machine learning models.
- Ray's ecosystem includes a wide range of libraries and frameworks, such as RLlib for reinforcement learning, Tune for hyperparameter optimization, and Serve for model serving.
- Ray's architecture is designed to be scalable and fault-tolerant, making it suitable for large-scale distributed applications.
Cons of Ray
- The learning curve for Ray can be steeper than PyTorch's, as it requires understanding of distributed systems concepts and Ray's specific APIs.
- Ray's focus on distributed computing may make it overkill for smaller-scale projects that don't require the advanced features it provides.
Code Comparison
PyTorch RL:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
class PolicyNetwork(nn.Module):
def __init__(self, state_size, action_size):
super(PolicyNetwork, self).__init__()
self.fc1 = nn.Linear(state_size, 64)
self.fc2 = nn.Linear(64, action_size)
def forward(self, state):
x = torch.relu(self.fc1(state))
x = self.fc2(x)
return Categorical(logits=x)
Ray:
import ray
from ray.rllib.agents.ppo import PPOTrainer
from ray.tune.registry import register_env
def env_creator(config):
return MyEnv()
register_env("my_env", env_creator)
config = {
"env": "my_env",
"num_workers": 4,
"gamma": 0.99,
"lambda": 0.95,
"clip_param": 0.2,
"kl_target": 0.01,
}
trainer = PPOTrainer(config=config)
OpenAI Baselines: high-quality implementations of reinforcement learning algorithms
Pros of Baselines
- Baselines provides a wide range of pre-implemented reinforcement learning algorithms, including A2C, ACER, ACKTR, DDPG, DQN, GAIL, PPO, and TRPO.
- The codebase is well-documented and easy to understand, making it a great resource for learning and experimenting with different RL algorithms.
- Baselines includes a variety of environments, such as Atari, MuJoCo, and Roboschool, which can be used for benchmarking and testing RL models.
Cons of Baselines
- Baselines is primarily focused on classic RL algorithms and may not have the latest advancements in the field.
- The codebase is not as actively maintained as some other RL libraries, and there may be compatibility issues with newer versions of dependencies.
- Baselines does not provide the same level of flexibility and customization as PyTorch RL, which is built on top of the PyTorch framework.
Code Comparison
PyTorch RL:
import torch.nn as nn
class PolicyNetwork(nn.Module):
def __init__(self, state_size, action_size, hidden_size=64):
super(PolicyNetwork, self).__init__()
self.fc1 = nn.Linear(state_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, action_size)
def forward(self, state):
x = F.relu(self.fc1(state))
return F.softmax(self.fc2(x), dim=1)
Baselines:
import tensorflow as tf
class PolicyNetwork(tf.keras.Model):
def __init__(self, state_size, action_size, hidden_size=64):
super(PolicyNetwork, self).__init__()
self.fc1 = tf.keras.layers.Dense(hidden_size, activation='relu')
self.fc2 = tf.keras.layers.Dense(action_size, activation='softmax')
def call(self, state):
x = self.fc1(state)
return self.fc2(x)
Dopamine is a research framework for fast prototyping of reinforcement learning algorithms.
Pros of Dopamine
- Dopamine provides a collection of reinforcement learning agents and environments, making it easier to experiment with different algorithms and setups.
- The library includes a variety of common benchmark tasks, such as Atari games, which can be used to evaluate the performance of different agents.
- Dopamine is well-documented and includes detailed tutorials and examples, making it more accessible for researchers and developers new to reinforcement learning.
Cons of Dopamine
- Dopamine is primarily focused on classic reinforcement learning tasks and may not be as well-suited for more complex or specialized applications.
- The library is primarily developed and maintained by Google, which may limit the diversity of contributions and perspectives compared to a more open-source project.
- Dopamine may have a steeper learning curve for developers who are more familiar with PyTorch's ecosystem and tooling.
Code Comparison
PyTorch RL:
import torch.nn as nn
class PolicyNetwork(nn.Module):
def __init__(self, state_size, action_size):
super(PolicyNetwork, self).__init__()
self.fc1 = nn.Linear(state_size, 64)
self.fc2 = nn.Linear(64, action_size)
def forward(self, state):
x = F.relu(self.fc1(state))
return F.softmax(self.fc2(x), dim=1)
Dopamine:
import tensorflow as tf
class DQNNetwork(tf.keras.Model):
def __init__(self, num_actions):
super(DQNNetwork, self).__init__()
self.conv1 = tf.keras.layers.Conv2D(32, (8, 8), strides=(4, 4), activation='relu')
self.conv2 = tf.keras.layers.Conv2D(64, (4, 4), strides=(2, 2), activation='relu')
self.conv3 = tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), activation='relu')
self.flatten = tf.keras.layers.Flatten()
self.fc1 = tf.keras.layers.Dense(512, activation='relu')
self.fc2 = tf.keras.layers.Dense(num_actions)
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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
Recent highlights
TorchRL 0.13 and the preceding development cycle bring several user-visible improvements that are worth surfacing up front:
- faster recurrent RL paths, including scan and Triton GRU/LSTM reset handling;
- custom MuJoCo environments, satellite examples, and macro-control policies;
- stronger multi-agent coverage through MAPPO, IPPO,
MultiAgentGAE, value-normalization utilities, and mixer configs; - better collector and replay-buffer ergonomics, including async prioritized writes, ordered storage access, compact observations, HER, and optional CUDA wheels for CUDA-based prioritized replay-buffer kernels;
- new transforms and value-estimator improvements such as
ActionScaling,FlattenAction,NextObservationDelta, compact shifted estimators, and chunked forwards.
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
PendulumEnvand custom MuJoCo tasks. - 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, 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.
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.
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, HER, or custom storage layouts.
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()
Replay buffers understand TensorDict structure, so they can store trajectories, nested agent data, recurrent states, HER relabeling metadata, or offline datasets without flattening everything into parallel Python containers.
Modules, distributions, and policies
TorchRL modules are ordinary PyTorch modules with explicit input and output keys. The library provides actors, critics, actor-critic operators, recurrent modules, distribution wrappers, exploration modules, world models, decision transformers, robot-learning models, and helper utilities for inferring specs from environments.
A stochastic actor can be assembled from familiar PyTorch layers:
from tensordict.nn import TensorDictModule
from tensordict.nn.distributions import NormalParamExtractor
from torch import nn
from torchrl.modules import ProbabilisticActor, TanhNormal
params = TensorDictModule(
nn.Sequential(
nn.LazyLinear(256),
nn.Tanh(),
nn.Linear(256, 2),
NormalParamExtractor(),
),
in_keys=["observation"],
out_keys=["loc", "scale"],
)
actor = ProbabilisticActor(
params,
in_keys=["loc", "scale"],
out_keys=["action"],
distribution_class=TanhNormal,
distribution_kwargs={"low": -1.0, "high": 1.0},
return_log_prob=True,
)
The explicit key contract makes it clear what data a module consumes and produces, and it allows losses, collectors, and transforms to be reconfigured without editing the model itself.
Objectives, returns, and trainers
TorchRL objectives are loss modules that read TensorDict keys, compute losses, and expose configurable key mappings. They cover policy-gradient methods, actor-critic algorithms, Q-learning, offline RL, imitation learning, model-based RL, and multi-agent RL.
Examples include PPO, SAC, DQN, TD3, REDQ, IQL, CQL, Decision Transformer, Dreamer, CrossQ, GAIL, behavior cloning, ACT, MAPPO, IPPO, and QMIX/VDN. Value-estimator utilities provide GAE, TD(lambda), V-trace, lambda returns, multi-agent advantages, and vectorized return computation.
from torchrl.objectives import ClipPPOLoss
from torchrl.objectives.value import GAE
loss = ClipPPOLoss(actor_network=actor, critic_network=critic)
advantage = GAE(value_network=critic, gamma=0.99, lmbda=0.95)
data = advantage(data)
losses = loss(data)
loss_value = losses["loss_objective"] + losses["loss_critic"] + losses["loss_entropy"]
For higher-level workflows, TorchRL also provides trainer utilities and Hydra configuration dataclasses that assemble environments, networks, collectors, losses, optimizers, loggers, hooks, and schedules into reproducible recipes.
Multi-agent, model-based, and imitation learning
Multi-agent data is represented as TensorDict structure rather than a separate
parallel convention. Agent observations, actions, rewards, masks, and shared
state can live under nested keys such as ("agents", "observation"), while
losses and modules declare which keys they use.
TorchRL supports multi-agent environments and algorithms through VMAS,
PettingZoo, Melting Pot, SMACv2, OpenSpiel, multi-agent trainers, and dedicated
objectives. The 0.13 line adds MAPPO, IPPO, MultiAgentGAE, ValueNorm,
PopArtValueNorm, RunningValueNorm, and cross-agent critic utilities.
The same component style also covers model-based and imitation-learning work: Dreamer/DreamerV3 objectives and RSSM modules, Decision Transformer components, behavior cloning losses, and ACT-style action chunking all share the same TensorDict and key-dispatch conventions as the online RL algorithms.
Additional specialized workflows
TorchRL also includes support for specialized workflows, including LLM post-training experiments. The LLM stack provides conversation containers, Hugging Face/vLLM/SGLang integration points, GRPO and SFT objectives, async collectors, weight-update helpers, and tool-use transforms. Entry points include the LLM reference and the GRPO implementation.
Performance and PyTorch integration
TorchRL is designed to stay close to PyTorch execution. Components are
TensorDict-aware, vectorized where possible, and increasingly friendly to
torch.compile, CUDA, shared memory, memmaps, and distributed execution.
Performance-sensitive areas include:
- vectorized return and advantage computation;
- recurrent GRU/LSTM reset handling with scan and Triton backends;
- compact sequence layouts for recurrent value estimation;
- async collectors and policy weight synchronization;
- prioritized replay and CUDA-aware replay-buffer paths;
- memmap-backed data movement for large offline or distributed jobs.
What is new in TorchRL 0.13
TorchRL 0.13 is a broad release. The most impactful changes are in recurrent RL performance, MuJoCo-native workflows, multi-agent training, model-based and imitation-learning components, replay/collector throughput, and compatibility with old or optional dependency stacks.
Recurrent RL
- Triton and scan recurrent backends for GRU/LSTM reset handling.
- Recurrent integration tests and a recurrent state lifecycle guide.
- Compact and shifted value-estimator improvements, chunked forwards, and a dynamic value-estimator registry across loss modules.
- Recurrent matmul precision controls exposed through public module utilities.
MuJoCo, robotics, and macro control
- Custom MuJoCo environments with selectable physics backends.
- New
MujocoEnvtask base plus locomotion tasks,SatelliteEnv, andCubeBowlEnv. - Satellite MuJoCo SAC examples.
- Macro-control primitives and tutorials for low-frequency semantic actions expanded into multi-step low-level control sequences.
Multi-agent, imitation, and model-based RL
- MAPPO and IPPO losses.
MultiAgentGAEand value-normalization utilities.- DreamerV3 losses and RSSM V3 modules.
BCLoss,ACTLoss, andACTModelfor behavior cloning and action chunking.- QMIX/VDN trainer configuration support and improved multi-agent trainer ergonomics.
Data, transforms, and compatibility
- HER support through
HERReplayBufferandHindsightStrategy. - Action and observation transforms such as
ActionScaling,FlattenAction,ExpandAs,NextObservationDelta,NextStateReconstructor, andTerminateTransform. - Async prioritized replay-buffer writes, ordered read/write APIs, optional trajectory IDs, compact observations, and safer collector weight syncs.
- Compatibility fixes across Gym/Atari, PettingZoo, Robohive, optional dependency, setup, documentation, vLLM, and SGLang workflows.
Where to start
| If you want to... | Start with... |
|---|---|
| Learn the basic environment and TensorDict loop | Getting started and the quick demo above |
| Train a classic continuous-control agent | PPO, SAC, or TD3 implementations |
| Build custom environment preprocessing | Environment transforms |
| Scale data collection | Collectors and distributed collectors |
| Store large or prioritized data | Replay buffers |
| Work with recurrent policies | Recurrent modules and state lifecycle docs |
| Train multi-agent systems | Multi-agent objectives and multi-agent examples |
| Explore MuJoCo macro policies | Macro primitives and MuJoCo tutorials |
| Try language-model post-training experiments | LLM reference and GRPO |
Installation
TorchRL 0.13 targets Python 3.10+, PyTorch 2.1+, and TensorDict 0.13.x.
Install the stable release:
pip install torchrl
This standard PyPI wheel is the right default for most users, including CPU
prioritized replay buffers and workloads that do not use prioritized replay.
Starting with TorchRL 0.13, Linux CUDA wheels are also published for users who
want the CUDA-based prioritized replay-buffer implementations. Install the
CUDA wheel from the PyTorch wheel index that matches your PyTorch CUDA runtime
(replace cu128 with the CUDA build you use):
pip install "torchrl==0.14.0+cu128" --extra-index-url https://download.pytorch.org/whl/cu128
The CUDA wheel is optional: if you do not need CUDA prioritized replay buffers,
or if your prioritized replay buffers run on CPU, keep using pip install torchrl.
Install common optional dependencies:
pip install "torchrl[utils]" # Hydra, logging, and development utilities
pip install "torchrl[gym_continuous]" # Gymnasium continuous-control environments
pip install "torchrl[atari]" # Atari support
pip install "torchrl[offline-data]" # Offline datasets and data helpers
pip install "torchrl[marl]" # Multi-agent environment libraries
pip install "torchrl[llm-vllm]" # LLM API with vLLM backend on Linux
pip install "torchrl[llm-sglang]" # LLM API with SGLang backend on Linux
Some optional libraries are platform- or Python-version-specific. If you are building a reproducible environment, install PyTorch first from the appropriate PyTorch installation selector, then install TorchRL and the optional extras you need.
Install the nightly builds when working against nightly PyTorch:
pip install --pre tensordict-nightly torchrl-nightly
For local development, keep the TorchRL and TensorDict checkouts on compatible branches and avoid re-resolving an already selected PyTorch build:
git clone https://github.com/pytorch/tensordict
git clone https://github.com/pytorch/rl
uv pip install --no-deps -e tensordict
uv pip install --no-deps -e rl
The C++ extension paths used by prioritized replay buffers require a compatible PyTorch version. If you see undefined-symbol errors, consult the versioning issues guide.
Documentation and learning resources
Introductory material:
Examples, tutorials, and implementations
TorchRL ships examples for small features and complete training recipes:
- SOTA implementations for PPO, SAC, DQN, TD3, REDQ, Decision Transformer, Dreamer, CrossQ, GAIL, IMPALA, multi-agent algorithms, GRPO, and more.
- Examples for distributed collectors, replay buffers, RLHF, MuJoCo satellite control, and other focused workflows.
- Tutorials for environment design, transforms, collectors, losses, recurrent state handling, MuJoCo macros, and end-to-end training.
The implementations are meant to be readable starting points, not black-box benchmarks. They show how TorchRL components fit together and can be copied into research code when a full trainer abstraction is not the right fit.
Ecosystem and publications
TorchRL is domain-agnostic and is used across robotics, control, simulation, drug discovery, multi-agent RL, combinatorial optimization, and research infrastructure. Selected projects and papers include:
- ACEGEN: Reinforcement learning of generative chemical agents for drug discovery.
- BenchMARL: Benchmarking multi-agent reinforcement learning.
- BricksRL: A platform for democratizing robotics and reinforcement learning research and education with LEGO.
- OmniDrones: An efficient and flexible platform for reinforcement learning in drone control.
- RL4CO: Reinforcement learning for combinatorial optimization.
- Robohive: A unified framework for robot learning.
Citation
If you use TorchRL, please cite:
@misc{bou2023torchrl,
title={TorchRL: A data-driven decision-making library for PyTorch},
author={Albert Bou and Matteo Bettini and Sebastian Dittert and Vikash Kumar and Shagun Sodhani and Xiaomeng Yang and Gianni De Fabritiis and Vincent Moens},
year={2023},
eprint={2306.00577},
archivePrefix={arXiv},
primaryClass={cs.LG}
}
Asking questions
If you find a bug, please open an issue in this repository. For broader RL in PyTorch questions, use the PyTorch reinforcement learning forum.
Contributing
Contributions are welcome. See CONTRIBUTING.md for the full contribution guide and the call for contributions for open areas where help is especially useful.
To work on an open issue, comment /assign on the issue. This will assign the
issue to you.
Trusted collaborators
TorchRL is maintained by Vincent Moens (vmoens).
The following trusted collaborators are also available for review guidance and
contributor advice:
If you would like to be added to this list, reach out to
Vincent Moens (vmoens).
For local development, install pre-commit hooks with:
pre-commit install
Status and license
TorchRL is released as a PyTorch beta feature. Breaking changes can happen, but TorchRL aims to introduce them with deprecation warnings over multiple release cycles.
TorchRL is licensed under the MIT License. See LICENSE for details.
Top Related Projects
A toolkit for developing and comparing reinforcement learning algorithms.
TensorFlow Reinforcement Learning
Ray is an AI compute engine. Ray consists of a core distributed runtime and a set of AI Libraries for accelerating ML workloads.
OpenAI Baselines: high-quality implementations of reinforcement learning algorithms
Dopamine is a research framework for fast prototyping of reinforcement learning algorithms.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot