Examples#

This page indexes the Python scripts in RLlib’s examples folder, which demonstrate the library’s different use cases and features.

Note

RLlib is transitioning from the old to the new API stack. The Ray team has translated most example scripts to the new stack and tags those still on the old stack with a # @OldAPIStack comment at the top. Moving all example scripts to the new stack is a work in progress.

Note

To report a broken new API stack example or add an example to this page, create an issue in the RLlib GitHub repository.

Folder structure#

The examples folder has several sub-directories, described below.

How to run an example script#

Most example scripts are self-executable, so you can cd into the directory and run the script as-is with Python:

$ cd ray/rllib/examples/multi_agent
$ python multi_agent_pendulum.py --num-agents=2

Use the --help command-line argument to print each script’s supported command-line options.

Most scripts share a common subset of command-line arguments. For example, use --num-env-runners to scale the number of EnvRunner actors, --no-tune to run without Ray Tune, --wandb-key to log to WandB, or --verbose to control log chattiness.

All example sub-folders#

Actions#

  • Auto-regressive actions: Configures an RLModule that generates actions in an autoregressive manner, where the second component of an action depends on the previously sampled first component of the same action.

  • Custom action distribution class: Demonstrates how to write a custom action distribution class, taking an additional temperature parameter on top of a Categorical distribution, and how to configure this class inside your RLModule implementation. Further explains how to define different such classes for the different forward methods of your RLModule in case you need more granularity.

  • Nested action spaces: Sets up an environment with nested action spaces using custom single- or multi-agent configurations. This example demonstrates how RLlib manages complex action structures, such as multi-dimensional or hierarchical action spaces.

Algorithms#

Checkpoints#

Connectors#

Note

RLlib rewrote the Connector API from scratch for the new API stack. It calls connector pieces and pipelines ConnectorV2 to distinguish them from the Connector class, which works only on the old API stack.

  • Flatten and one-hot observations: Demonstrates how to one-hot discrete observation spaces or flatten complex observations, Dict or Tuple, so RLlib can process arbitrary observation data as flattened 1D vectors. Useful for environments with complex, discrete, or hierarchical observations.

  • Observation frame-stacking: Implements frame stacking, where N consecutive frames stack together to provide temporal context to the agent. This technique is common in environments with continuous state changes, such as video frames in Atari games. Frame stacking with connectors is more efficient because it avoids sending large observation tensors through Ray remote calls.

  • Mean/Std filtering: Adds mean and standard deviation normalization for observations, shifting by the mean and dividing by std-dev. This type of filtering can improve learning stability in environments with highly variable state magnitudes by scaling observations to a normalized range.

  • Multi-agent observation preprocessor enhancing non-Markovian observations to Markovian ones: A multi-agent preprocessor enhances the per-agent observations of a multi-agent env, which by themselves are non-Markovian, partial observations and converts them into Markovian observations by adding information from the respective other agent. A policy can train optimally only with this additional information.

  • Prev-actions, prev-rewards connector: Augments observations with previous actions and rewards, giving the agent a short-term memory of past events, which can improve decision-making in partially observable or sequentially dependent tasks.

  • Single-agent observation preprocessor: A connector alters the CartPole-v1 environment observations from the Markovian 4-tuple of x-pos, angular-pos, x-velocity, and angular-velocity to a simpler, non-Markovian 2-tuple of only x-pos and angular-pos. You can solve the resulting problem only with a memory or stateful model, such as an LSTM.

Curiosity#

  • Count-based curiosity: Implements count-based intrinsic motivation to encourage exploration of less visited states. Using curiosity is beneficial in sparse-reward environments where agents may struggle to find rewarding paths. However, count-based methods are only feasible for environments with small observation spaces.

  • Euclidean distance-based curiosity: Uses Euclidean distance between states and the initial state to measure novelty, encouraging exploration by rewarding the agent for reaching “far away” regions of the environment. Suitable for sparse-reward tasks, where diverse exploration is key to success.

  • Intrinsic-curiosity-model (ICM) based curiosity: Adds an Intrinsic Curiosity Model (ICM) that learns to predict the next state as well as the action in between two states to measure novelty. The higher the loss of the ICM, the higher the “novelty” and thus the intrinsic reward. Ideal for complex environments with large observation spaces where reward signals are sparse.

Curriculum learning#

  • Custom env rendering method: Demonstrates curriculum learning, where the environment difficulty increases as the agent improves. With this approach, agents master simpler tasks before progressing to harder ones, ideal for environments with hierarchical or staged difficulties. See also the curriculum learning how-to.

  • Curriculum learning for Atari Pong: Demonstrates curriculum learning for Atari Pong, using the frameskip to increase the difficulty of the task. With this approach, agents master slower reactions at a lower frameskip before progressing to faster ones at a higher frameskip. See also the curriculum learning how-to.

Debugging#

  • Deterministic sampling and training: Demonstrates how to seed an experiment through the algorithm config. RLlib passes the seed to all components that have a copy of the RL environment and the RLModule, so these components behave deterministically. With a seed, train results should become repeatable. Some algorithms, such as APPO, rely on asynchronous sampling combined with Ray network communication and always behave stochastically, whether or not you set a seed.

Environments#

  • Async gym vectorization, parallelizing sub-environments: Shows how the gym_env_vectorize_mode config setting can significantly speed up your EnvRunner actors, if your RL environment is slow and you’re using num_envs_per_env_runner > 1. The performance gain comes from running each sub-environment in its own process.

  • Custom env rendering method: Demonstrates how to add a custom render() method to a custom environment to visualize agent interactions.

  • Custom gymnasium env: Implements a custom gymnasium environment from scratch, showing how to define observation and action spaces, arbitrary reward functions, and step and reset logic.

  • Env connecting to RLlib through a tcp client: An external environment, running outside of RLlib and acting as a client, connects to RLlib as a server. The external env performs its own action inference using an ONNX model, sends collected data back to RLlib for training, and periodically receives model updates from RLlib.

  • Env rendering and recording: Illustrates environment rendering and recording setups in RLlib, capturing visual outputs for later review, such as on WandB. This is essential for tracking agent behavior during training.

  • Env with protobuf observations: Uses Protobuf for observations, demonstrating an advanced way of handling serialized data in environments. This approach is useful for integrating complex external data sources as observations.

Evaluation#

  • Custom evaluation: Configures custom evaluation metrics for agent performance, so you can define specific success criteria beyond standard RLlib evaluation metrics.

  • Evaluation parallel to training: Runs evaluation episodes in parallel with training, reducing training time by offloading evaluation to separate processes. This method is beneficial when you need frequent evaluation without interrupting learning.

Fault tolerance#

  • Crashing and stalling env: Simulates an environment that randomly crashes or stalls, so you can test RLlib’s fault-tolerance mechanisms. This script is useful for evaluating how RLlib handles interruptions and recovers from unexpected failures during training.

GPUs for training and sampling#

  • Float16 training and inference: Configures a setup for float16 training and inference, optimizing performance by reducing memory usage and speeding up computation. This is especially useful for large-scale models on compatible GPUs.

  • Fractional GPUs per Learner: Demonstrates allocating fractional GPUs to individual learners for finer resource allocation in multi-model setups. Useful for saving resources when training smaller models, many of which can fit on a single GPU.

  • Mixed precision training and float16 inference: Uses mixed precision, float32 and float16, for training, while switching to float16 precision for inference, balancing stability during training with performance improvements during evaluation.

  • Using GPUs on EnvRunners: Demonstrates how EnvRunner instances, single- or multi-agent, can request GPUs through the config.env_runners(num_gpus_per_env_runner=..) setting.

Hierarchical training#

  • Hierarchical RL training: Demonstrates a hierarchical RL setup inspired by automatic subgoal discovery and subpolicy specialization. A high-level policy selects subgoals and assigns one of three specialized low-level policies to achieve them within a time limit, encouraging specialization and efficient task-solving. The agent has to navigate a complex grid-world environment. The example highlights the advantages of hierarchical learning over flat approaches by demonstrating significantly improved learning performance in challenging, goal-oriented tasks.

Inference of models or policies#

Learners#

  • Custom loss function, simple: Implements a custom loss function for training, demonstrating how to define tailored loss objectives for specific environments or behaviors.

  • Custom torch learning rate schedulers: Adds learning rate scheduling to PPO, showing how to adjust the learning rate dynamically using PyTorch schedulers for improved training stability.

  • Separate learning rate and optimizer for value function: Configures a separate learning rate and optimizer for the value function versus the policy network, for differentiated training dynamics between policy and value estimation in RL algorithms.

Metrics#

Multi-agent RL#

  • Custom heuristic policy: Demonstrates running a hybrid policy setup within the MultiAgentCartPole environment, where one agent follows a hand-coded random policy while another agent trains with PPO. This example highlights integrating static and dynamic policies, suitable for environments with a mix of fixed-strategy and adaptive agents.

  • Different observation and action spaces for different agents: Configures agents with differing observation and action spaces within the same environment, demonstrating RLlib’s support for heterogeneous agents with varying space requirements in a single multi-agent environment. For another example that uses connectors and covers the same topic of agents having different spaces, see the multi-agent observation preprocessor example.

  • Grouped agents, two-step game: Implements a multi-agent, grouped setup within a two-step game environment from the QMIX paper. N agents form M teams in total, where N is at least M, and agents in each team share rewards and one policy. This example demonstrates RLlib’s ability to manage collective objectives and interactions among grouped agents.

  • Multi-agent CartPole: Runs a multi-agent version of the CartPole environment with each agent independently learning to balance its pole. This example serves as a foundational test for multi-agent reinforcement learning scenarios in simple, independent tasks.

  • Multi-agent Pendulum: Extends the classic Pendulum environment into a multi-agent setting, where multiple agents attempt to balance their respective pendulums. This example highlights RLlib’s support for environments with replicated dynamics but distinct agent policies.

  • PettingZoo independent learning: Integrates RLlib with PettingZoo to facilitate independent learning among multiple agents. Each agent independently optimizes its policy within a shared environment.

  • PettingZoo parameter sharing: Uses PettingZoo for an environment where all agents share a single policy.

  • Rock-paper-scissors heuristic vs learned: Simulates a rock-paper-scissors game with one heuristic-driven agent and one learning agent. It provides insights into performance when combining fixed and adaptive strategies in adversarial games.

  • Rock-paper-scissors learned vs learned: Sets up a rock-paper-scissors game where you train both agents to learn strategies for playing against each other. Useful for evaluating performance in simple adversarial settings.

  • Self-play, league-based, with OpenSpiel: Uses OpenSpiel to demonstrate league-based self-play, where agents play against various versions of themselves, frozen or in-training, to improve through competitive interaction.

  • Self-play with Footsies and PPO algorithm: Implements self-play with the Footsies environment, a two-player zero-sum game. This example demonstrates connecting RLlib to the external binaries that run the game engine and setting up a multi-agent self-play training scenario.

  • Self-play with OpenSpiel: Similar to the league-based self-play, but simpler. This script uses OpenSpiel for two-player games, where agents improve through direct self-play without building a complex, structured league.

Offline RL#

Ray Serve and RLlib#

  • Using Ray Serve with RLlib: Integrates RLlib with Ray Serve, demonstrating how to deploy trained RLModule instances as RESTful services. This setup is ideal for deploying models in production environments with API-based interactions.

Ray Tune and RLlib#

  • Custom experiment: Configures a custom experiment with Ray Tune, demonstrating advanced options for custom training and evaluation phases.

  • Custom logger: Shows how to implement a custom logger within Ray Tune, so you can define specific logging behaviors and outputs during training.

  • Custom progress reporter: Demonstrates a custom progress reporter in Ray Tune to track and display specific training metrics or status updates in a customized format.

RLModules#

Tuned examples#

The tuned examples folder contains Python config files that you can execute analogously to all other example scripts described here to run tuned learning experiments for the different algorithms and environment types.

For example, see this tuned Atari example for PPO, which learns to solve the Pong environment in roughly 5 minutes. You can run it as follows on a single g5.24xlarge or g6.24xlarge machine with 4 GPUs and 96 CPUs:

$ cd ray/rllib/examples/algorithms/ppo
$ python atari_ppo.py --env=ale_py:ALE/Pong-v5 --num-learners=4 --num-env-runners=95

RLlib’s daily or weekly release tests also use some of the files in this folder.

Community examples#

Note

The community examples listed here all refer to the old API stack of RLlib.

  • Arena AI: A General Evaluation Platform and Building Toolkit for Single/Multi-Agent Intelligence with RLlib-generated baselines.

  • CARLA: Example of training autonomous vehicles with RLlib and CARLA simulator.

  • The Emergence of Adversarial Communication in Multi-Agent Reinforcement Learning: Using Graph Neural Networks and RLlib to train multiple cooperative and adversarial agents to solve the “cover the area”-problem, learning how best to communicate, or in the adversarial case how to disturb communication. See the code.

  • Flatland: A dense traffic simulating environment with RLlib-generated baselines.

  • GFootball: Example of setting up a multi-agent version of GFootball with RLlib.

  • mobile-env: An open, minimalist Gymnasium environment for autonomous coordination in wireless mobile networks. Includes an example notebook using Ray RLlib for multi-agent RL with mobile-env.

  • Neural MMO: A multi-agent AI research environment inspired by Massively Multiplayer Online (MMO) role-playing games. These are self-contained worlds featuring thousands of agents per persistent macrocosm, diverse skilling systems, local and global economies, complex emergent social structures, and ad-hoc high-stakes single and team-based conflict.

  • NeuroCuts: Example of building packet classification trees using RLlib / multi-agent in a bandit-like setting.

  • NeuroVectorizer: Example of learning optimal LLVM vectorization compiler pragmas for loops in C and C++ code using RLlib.

  • Roboschool / SageMaker: Example of training robotic control policies in SageMaker with RLlib.

  • Sequential Social Dilemma Games: Example of using the multi-agent API to model several social dilemma games.

  • Simple custom environment for single RL with Ray and RLlib: Create a custom environment and train a single agent RL using Ray 2.0 with Tune.

  • StarCraft2: Example of training in StarCraft2 maps with RLlib / multi-agent.

  • Traffic Flow: Example of optimizing mixed-autonomy traffic simulations with RLlib / multi-agent.

Blog posts#

Note

The blog posts listed here all refer to the old API stack of RLlib.