Key concepts#
This page introduces the key concepts and overall architecture of RLlib.
The central component of RLlib is the Algorithm class, which acts as a runtime for your RL experiments. Your gateway into an Algorithm is the AlgorithmConfig (cyan) class, where you manage configuration settings such as the learning rate or model architecture. Most Algorithm objects have EnvRunner actors (blue) to collect training samples from the RL environment and Learner actors (yellow) to compute gradients and update your models. The algorithm synchronizes model weights after an update.
AlgorithmConfig and Algorithm#
Tip
This section is a quick overview of RLlib AlgorithmConfigs and Algorithms. See the detailed description of the Algorithm class.
The RLlib Algorithm class serves as a runtime for your RL experiments. It brings together every component needed to learn an optimal solution to your RL environment and exposes Python APIs for controlling your experiment runs.
Each RLlib Algorithm type has its own AlgorithmConfig class, which you use to configure settings in a checked, type-safe manner. For example, to configure a PPO (“Proximal Policy Optimization”) algorithm instance, use the PPOConfig class.
During its construction, the Algorithm first sets up its EnvRunnerGroup, containing n EnvRunner actors, and its LearnerGroup, containing m Learner actors. This way, you can scale up sample collection and training, respectively, from a single core to many thousands of cores in a cluster.
See the scaling guide.
You have two ways to interact with and run an Algorithm:
You can create and manage an instance of it directly through the Python API.
Because the
Algorithmclass is a subclass of the Tune Trainable API, you can use Ray Tune to manage your experiment and tune hyperparameters.
The following examples demonstrate this on RLlib’s PPO (“Proximal Policy Optimization”) algorithm:
from ray.rllib.algorithms.ppo import PPOConfig
# Configure.
config = (
PPOConfig()
.environment("CartPole-v1")
.training(
train_batch_size_per_learner=2000,
lr=0.0004,
)
)
# Build the Algorithm.
algo = config.build()
# Train for one iteration, which is 2000 timesteps (1 train batch).
print(algo.train())
from ray import tune
from ray.rllib.algorithms.ppo import PPOConfig
# Configure.
config = (
PPOConfig()
.environment("CartPole-v1")
.training(
train_batch_size_per_learner=2000,
lr=0.0004,
)
)
# Train through Ray Tune.
results = tune.Tuner(
"PPO",
param_space=config,
# Train for 2000 timesteps (1 iteration).
run_config=tune.RunConfig(stop={"num_env_steps_sampled_lifetime": 2000}),
).fit()
RL environments#
Tip
This section is a quick overview of RL environments. See the detailed description of how to use RL environments in RLlib.
A reinforcement learning (RL) environment is a structured space, such as a simulator or a controlled section of the real world, in which one or more agents interact and learn to achieve specific goals. The environment defines an observation space, an action space, a reward function, and the rules that govern transitions when agents apply actions. The observation space is the structure and shape of observable tensors at each timestep. The action space defines the actions available to the agents at each timestep.
A simple RL environment where an agent starts with an initial observation returned by the reset() method.
The agent, possibly controlled by a neural network policy, sends actions, such as right or jump,
to the environment’s step() method, which returns a reward. Here, the reward values are +5 for reaching the goal
and 0 otherwise. The environment also returns a boolean flag indicating whether the episode is complete.#
Environments vary in complexity, from simple tasks such as navigating a grid world to highly intricate systems such as autonomous driving simulators, robotic control environments, or multi-agent games.
During a training iteration, RLlib interacts with the environment by playing through many episodes to collect data, such as observations, actions, rewards, and done flags, as shown in the preceding figure. It then converts this episode data into a train batch for model updates. These updates change the agents’ behaviors to maximize the sum of rewards over the agents’ lifetimes.
RLModules#
Tip
This section is a quick overview of RLlib RLModules. See the detailed description of the RLModule class.
RLModules are deep-learning framework-specific neural network wrappers.
RLlib’s EnvRunners use them to compute actions when stepping through the RL environment, and RLlib’s Learners use RLModule instances to compute losses and gradients before updating them.
RLModule overview: (left) A minimal RLModule contains a neural network
and defines its forward exploration, inference, and training logic.
(right) In more complex setups, a MultiRLModule contains
many submodules, each itself an RLModule instance and
identified by a ModuleID, so you can implement arbitrarily complex multi-model and multi-agent algorithms.#
An RLModule carries the neural network models and defines how to use them during the three phases of its RL lifecycle. Exploration collects training data, inference computes actions during evaluation or in production, and training computes the loss function inputs.
You can use RLlib’s built-in default models and configure these as needed, for example to change the number of layers or the activation functions, or write your own custom models in PyTorch to implement any architecture and computation logic.
An RLModule inside an EnvRunner actor: The EnvRunner operates on its own copy of an
inference-only version of the RLModule, using it only to compute actions.#
Each EnvRunner actor, managed by the Algorithm’s EnvRunnerGroup, has a copy of your RLModule. Each Learner actor, managed by the Algorithm’s LearnerGroup, also has an RLModule copy.
The EnvRunner copy is normally in its inference_only version. To save memory, this version drops components that bare action computation doesn’t need, such as a value function estimate.
An RLModule inside a Learner actor: The Learner operates on its own copy of
an RLModule, computing the loss function inputs, the loss itself,
and the model’s gradients, then updating the RLModule
through the Learner’s optimizers.#
Episodes#
Tip
This section is a quick overview of Episodes. See the detailed description of the Episode classes.
RLlib sends all training data around in the form of Episodes.
The SingleAgentEpisode class describes single-agent trajectories. The MultiAgentEpisode class contains several such single-agent episodes and describes the stepping times and patterns of the individual agents with respect to each other.
Both Episode classes store the entire trajectory data generated while stepping through an RL environment. This data includes the observations, info dicts, actions, rewards, termination signals, and any model computations along the way, such as recurrent states, action logits, or action log probabilities.
Tip
See RLlib’s standardized column names.
Episodes don’t store any next obs information, because it always overlaps with the information under obs. This design saves almost 50% of memory, because observations are often the largest piece in a trajectory. The same is true for state_in and state_out information for stateful networks. RLlib keeps only the state_out key in the episodes.
Typically, RLlib generates episode chunks of size config.rollout_fragment_length through the EnvRunner actors in the Algorithm’s EnvRunnerGroup, and sends as many episode chunks to each Learner actor as required to build one training batch of exactly size config.train_batch_size_per_learner.
A typical SingleAgentEpisode object roughly looks as follows:
# A SingleAgentEpisode of length 20 has roughly the following schematic structure.
# Note that after these 20 steps, you have 20 actions and rewards, but 21 observations and info dicts
# due to the initial "reset" observation/infos.
episode = {
'obs': np.ndarray((21, 4), dtype=float32), # 21 due to additional reset obs
'infos': [{}, {}, {}, {}, .., {}, {}], # infos are always lists of dicts
'actions': np.ndarray((20,), dtype=int64), # Discrete(4) action space
'rewards': np.ndarray((20,), dtype=float32),
'extra_model_outputs': {
'action_dist_inputs': np.ndarray((20, 4), dtype=float32), # Discrete(4) action space
},
'is_terminated': False, # <- single bool
'is_truncated': True, # <- single bool
}
For complex observations, such as gym.spaces.Dict, the episode holds all observations in a struct analogous to the observation space, with NumPy arrays at the leaves of that dict. For example:
episode_w_complex_observations = {
'obs': {
"camera": np.ndarray((21, 64, 64, 3), dtype=float32), # RGB images
"sensors": {
"front": np.ndarray((21, 15), dtype=float32), # 1D tensors
"rear": np.ndarray((21, 5), dtype=float32), # another batch of 1D tensors
},
},
...
Because RLlib keeps all values in NumPy arrays, it can encode and transmit them efficiently across the network.
In multi-agent mode, the EnvRunnerGroup produces MultiAgentEpisode instances.
Note
The Ray team is working on a detailed description of the MultiAgentEpisode class.
EnvRunner: Combining RL environment and RLModule#
Given the RL environment and an RLModule, an EnvRunner produces lists of Episodes.
It does so by executing a classic environment interaction loop. Efficient sample collection can be hard to get right, especially with environment vectorization, stateful recurrent neural networks, or a multi-agent setting.
RLlib provides two built-in EnvRunner classes, SingleAgentEnvRunner and MultiAgentEnvRunner that automatically handle these complexities. RLlib picks the correct type based on your configuration, in particular the config.environment() and config.multi_agent() settings.
Tip
Call the is_multi_agent() method to find out whether your config is multi-agent.
RLlib bundles several EnvRunner actors through the EnvRunnerGroup API.
You can also use an EnvRunner standalone to produce lists of Episodes by calling its sample() method.
The following example creates a set of remote EnvRunner actors and uses them to gather experiences in parallel:
import tree # pip install dm_tree
import ray
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.env.single_agent_env_runner import SingleAgentEnvRunner
# Configure the EnvRunners.
config = (
PPOConfig()
.environment("Acrobot-v1")
.env_runners(num_env_runners=2, num_envs_per_env_runner=1)
)
# Create the EnvRunner actors.
env_runners = [
ray.remote(SingleAgentEnvRunner).remote(config=config)
for _ in range(config.num_env_runners)
]
# Gather lists of `SingleAgentEpisode`s (each EnvRunner actor returns one
# such list with exactly two episodes in it).
episodes = ray.get([
er.sample.remote(num_episodes=3)
for er in env_runners
])
# Two remote EnvRunners used.
assert len(episodes) == 2
# Each EnvRunner returns three episodes
assert all(len(eps_list) == 3 for eps_list in episodes)
# Report the returns of all episodes collected
for episode in tree.flatten(episodes):
print("R=", episode.get_return())
Learner: Combining RLModule, loss function, and optimizer#
Tip
This section is a quick overview of RLlib Learners. See the detailed description of the Learner class.
Given the RLModule and one or more optimizers and loss functions, a Learner computes losses and gradients, then updates the RLModule.
The input data for such an update step comes in as a list of episodes, which either the Learner’s own connector pipeline or an external one converts into the final train batch. For how these connector pipelines work, see ConnectorV2.
Learner instances are algorithm-specific, mostly due to the various loss functions used by different RL algorithms.
RLlib always bundles several Learner actors through the LearnerGroup API, automatically applying distributed data parallelism (DDP) on the training data. You can also use a Learner standalone to update your RLModule with a list of Episodes.
The following example creates a remote Learner actor and calls its update() method.
import gymnasium as gym
import ray
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig
# Configure the Learner.
config = (
PPOConfig()
.environment("Acrobot-v1")
.training(lr=0.0001)
.rl_module(model_config=DefaultModelConfig(fcnet_hiddens=[64, 32]))
)
# Get the Learner class.
ppo_learner_class = config.get_default_learner_class()
# Create the Learner actor.
learner_actor = ray.remote(ppo_learner_class).remote(
config=config,
module_spec=config.get_multi_rl_module_spec(env=gym.make("Acrobot-v1")),
)
# Build the Learner.
ray.get(learner_actor.build.remote())
# Perform an update from the list of episodes we got from the `EnvRunners` above.
learner_results = ray.get(learner_actor.update.remote(
episodes=tree.flatten(episodes)
))
print(learner_results["default_policy"]["policy_loss"])