Learner (Alpha)#
The Learner class abstracts the training logic of RLModules. It supports both gradient-based and non-gradient-based updates, such as polyak averaging. You can distribute the Learner with data-distributed parallel (DDP). The Learner does the following:
Facilitates gradient-based updates on RLModule.
Provides abstractions for non-gradient-based updates such as polyak averaging.
Reports training statistics.
Checkpoints the modules and optimizer states for durable training.
The Learner class supports data-distributed parallel training through the LearnerGroup API. The LearnerGroup maintains multiple copies of the same Learner with identical parameters and hyperparameters. Each Learner instance computes the loss and gradients on a shard of a sample batch, then accumulates the gradients across instances. For more about data-distributed parallel learning, see the PyTorch DDP tutorial.
The LearnerGroup also supports asynchronous training and distributed checkpointing for durability during training.
Enable the Learner API in RLlib experiments#
Adjust the training resources through the num_gpus_per_learner, num_cpus_per_learner, and num_learners arguments in AlgorithmConfig.
config = (
PPOConfig()
.learners(
num_learners=0, # Set this to greater than 1 to allow for DDP style updates.
num_gpus_per_learner=0, # Set this to 1 to enable GPU training.
num_cpus_per_learner=1,
)
)
Note
This feature is in alpha. If you migrate to this algorithm, enable the feature through AlgorithmConfig.api_stack(enable_rl_module_and_learner=True, enable_env_runner_and_connector_v2=True).
The following algorithms support Learner out of the box. To use this API with other algorithms, implement a custom Learner.
Basic usage#
Use the LearnerGroup utility to interact with multiple learners.
Construction#
If you enable the RLModule and Learner APIs through AlgorithmConfig, then calling build_algo() constructs a LearnerGroup for you. If you use these APIs standalone, construct the LearnerGroup as follows:
env = gym.make("CartPole-v1")
# Create an AlgorithmConfig object from which we can build the
# LearnerGroup.
config = (
PPOConfig()
# Number of Learner workers (Ray actors).
# Use 0 for no actors, only create a local Learner.
# Use >=1 to create n DDP-style Learner workers (Ray actors).
.learners(num_learners=1)
# Specify the learner's hyperparameters.
.training(
use_kl_loss=True,
kl_coeff=0.01,
kl_target=0.05,
clip_param=0.2,
vf_clip_param=0.2,
entropy_coeff=0.05,
vf_loss_coeff=0.5
)
)
# Construct a new LearnerGroup using our config object.
learner_group = config.build_learner_group(env=env)
env = gym.make("CartPole-v1")
# Create an AlgorithmConfig object from which we can build the
# Learner.
config = (
PPOConfig()
# Specify the Learner's hyperparameters.
.training(
use_kl_loss=True,
kl_coeff=0.01,
kl_target=0.05,
clip_param=0.2,
vf_clip_param=0.2,
entropy_coeff=0.05,
vf_loss_coeff=0.5
)
)
# Construct a new Learner using our config object.
learner = config.build_learner(env=env)
# Needs to be called on the learner before calling any functions.
learner.build()
Updates#
TIMESTEPS = {"num_env_steps_sampled_lifetime": 250}
# This is a blocking update.
results = learner_group.update(batch=DUMMY_BATCH, timesteps=TIMESTEPS)
# This is a non-blocking update. The results are returned in a future
# call to `update(..., async_update=True)`
_ = learner_group.update(batch=DUMMY_BATCH, async_update=True, timesteps=TIMESTEPS)
# Artificially wait for async request to be done to get the results
# in the next call to
# `LearnerGroup.update(..., async_update=True)`.
time.sleep(5)
results = learner_group.update(
batch=DUMMY_BATCH, async_update=True, timesteps=TIMESTEPS
)
# `results` is a list of n result dicts from various Learner actors.
assert isinstance(results, list), results
assert isinstance(results[0], dict), results
When updating a LearnerGroup, you can perform blocking or async updates on batches of data. Async updates are necessary for implementing async algorithms such as APPO or IMPALA.
# This is a blocking update (given a training batch).
result = learner.update(batch=DUMMY_BATCH, timesteps=TIMESTEPS)
When updating a Learner, you can only perform blocking updates on batches of data. You can perform non-gradient-based updates before or after the gradient-based ones by overriding before_gradient_based_update() and after_gradient_based_update().
Getting and setting state#
# Get the LearnerGroup's RLModule weights and optimizer states.
state = learner_group.get_state()
learner_group.set_state(state)
# Only get the RLModule weights.
weights = learner_group.get_weights()
learner_group.set_weights(weights)
Set or get the state dict of all learners through LearnerGroup.set_state or LearnerGroup.get_state. The state includes the neural network weights and the optimizer states on each learner. For example, an Adam optimizer’s state holds momentum information from recent gradients. To get or set only the weights of the RLModules of all learners, use the LearnerGroup.get_weights and LearnerGroup.set_weights APIs.
from ray.rllib.core import COMPONENT_RL_MODULE
# Get the Learner's RLModule weights and optimizer states.
state = learner.get_state()
# Note that `state` is now a dict:
# {
# COMPONENT_RL_MODULE: [RLModule's state],
# COMPONENT_OPTIMIZER: [Optimizer states],
# }
learner.set_state(state)
# Only get the RLModule weights (as numpy, not torch/tf).
rl_module_only_state = learner.get_state(components=COMPONENT_RL_MODULE)
# Note that `rl_module_only_state` is now a dict:
# {COMPONENT_RL_MODULE: [RLModule's state]}
learner.module.set_state(rl_module_only_state)
Set and get the entire state of a Learner with set_state() and get_state(). To get only the RLModule’s weights without the optimizer states, use the components=COMPONENT_RL_MODULE argument in get_state(), as the preceding code shows. To set only the RLModule’s weights without touching the optimizer states, use set_state() and pass in a dict, {COMPONENT_RL_MODULE: [RLModule's state]}, as the preceding code shows.
Checkpointing#
learner_group.save_to_path(LEARNER_GROUP_CKPT_DIR)
learner_group.restore_from_path(LEARNER_GROUP_CKPT_DIR)
Checkpoint the state of all learners in the LearnerGroup through save_to_path() and restore the state of a saved LearnerGroup through restore_from_path(). A LearnerGroup’s state includes the neural network weights and all optimizer states. Because the state of all Learner instances is identical, RLlib saves only the state from the first Learner.
learner.save_to_path(LEARNER_CKPT_DIR)
learner.restore_from_path(LEARNER_CKPT_DIR)
Checkpoint the state of a Learner through save_to_path() and restore the state of a saved Learner through restore_from_path(). A Learner’s state includes the neural network weights and all optimizer states.
Implementation#
The Learner class has many APIs for flexible implementation. The core ones you need to implement are:
Method |
Description |
|---|---|
Set up the optimizers for an RLModule. |
|
Calculate the loss for a gradient-based update to a module. |
|
Do non-gradient-based updates to an RLModule before the gradient-based ones, such as adding noise to your network. |
|
Do non-gradient-based updates to an RLModule after the gradient-based ones, such as updating a loss coefficient based on a schedule. |
Starter example#
A Learner that implements behavior cloning could look like the following:
class BCTorchLearner(TorchLearner):
@override(Learner)
def compute_loss_for_module(
self,
*,
module_id: ModuleID,
config: AlgorithmConfig = None,
batch: Dict[str, Any],
fwd_out: Dict[str, TensorType],
) -> TensorType:
# standard behavior cloning loss
action_dist_inputs = fwd_out[SampleBatch.ACTION_DIST_INPUTS]
action_dist_class = self._module[module_id].get_train_action_dist_cls()
action_dist = action_dist_class.from_logits(action_dist_inputs)
loss = -torch.mean(action_dist.logp(batch[SampleBatch.ACTIONS]))
return loss

