RPCDataCollector¶
- class torchrl.collectors.distributed.RPCDataCollector(create_env_fn, policy, *, frames_per_batch: int, total_frames: int = -1, device: torch.device | List[torch.device] = None, storing_device: torch.device | List[torch.device] = None, env_device: torch.device | List[torch.device] = None, policy_device: torch.device | List[torch.device] = None, max_frames_per_traj: int = -1, init_random_frames: int = -1, reset_at_each_iter: bool = False, postproc: Callable | None = None, split_trajs: bool = False, exploration_type: ExporationType = InteractionType.RANDOM, exploration_mode: str = None, collector_class=<class 'torchrl.collectors.collectors.SyncDataCollector'>, collector_kwargs=None, num_workers_per_collector=1, sync=False, slurm_kwargs=None, update_after_each_batch=False, max_weight_update_interval=-1, launcher='submitit', tcp_port=None, visible_devices=None, tensorpipe_options=None)[source]¶
An RPC-based distributed data collector.
Supports sync and async data collection.
- Parameters:
create_env_fn (Callable or List[Callabled]) – list of Callables, each returning an instance of
EnvBase
.policy (Callable) –
Policy to be executed in the environment. Must accept
tensordict.tensordict.TensorDictBase
object as input. IfNone
is provided, the policy used will be aRandomPolicy
instance with the environmentaction_spec
. Accepted policies are usually subclasses ofTensorDictModuleBase
. This is the recommended usage of the collector. Other callables are accepted too: If the policy is not aTensorDictModuleBase
(e.g., a regularModule
instances) it will be wrapped in a nn.Module first. Then, the collector will try to assess if these modules require wrapping in aTensorDictModule
or not. - If the policy forward signature matches any offorward(self, tensordict)
,forward(self, td)
orforward(self, <anything>: TensorDictBase)
(or any typing with a single argument typed as a subclass ofTensorDictBase
) then the policy won’t be wrapped in aTensorDictModule
.In all other cases an attempt to wrap it will be undergone as such:
TensorDictModule(policy, in_keys=env_obs_key, out_keys=env.action_keys)
.
- Keyword Arguments:
frames_per_batch (int) – A keyword-only argument representing the total number of elements in a batch.
total_frames (int) –
A keyword-only argument representing the total number of frames returned by the collector during its lifespan. If the
total_frames
is not divisible byframes_per_batch
, an exception is raised.Endless collectors can be created by passing
total_frames=-1
. Defaults to-1
(endless collector).device (int, str or torch.device, optional) – The generic device of the collector. The
device
args fills any non-specified device: ifdevice
is notNone
and any ofstoring_device
,policy_device
orenv_device
is not specified, its value will be set todevice
. Defaults toNone
(No default device). Lists of devices are supported.storing_device (int, str or torch.device, optional) – The remote device on which the output
TensorDict
will be stored. Ifdevice
is passed andstoring_device
isNone
, it will default to the value indicated bydevice
. For long trajectories, it may be necessary to store the data on a different device than the one where the policy and env are executed. Defaults toNone
(the output tensordict isn’t on a specific device, leaf tensors sit on the device where they were created). Lists of devices are supported.env_device (int, str or torch.device, optional) – The remote device on which the environment should be cast (or executed if that functionality is supported). If not specified and the env has a non-
None
device,env_device
will default to that value. Ifdevice
is passed andenv_device=None
, it will default todevice
. If the value as such specified ofenv_device
differs frompolicy_device
and one of them is notNone
, the data will be cast toenv_device
before being passed to the env (i.e., passing different devices to policy and env is supported). Defaults toNone
. Lists of devices are supported.policy_device (int, str or torch.device, optional) – The remote device on which the policy should be cast. If
device
is passed andpolicy_device=None
, it will default todevice
. If the value as such specified ofpolicy_device
differs fromenv_device
and one of them is notNone
, the data will be cast topolicy_device
before being passed to the policy (i.e., passing different devices to policy and env is supported). Defaults toNone
. Lists of devices are supported.max_frames_per_traj (int, optional) – Maximum steps per trajectory. Note that a trajectory can span across multiple batches (unless
reset_at_each_iter
is set toTrue
, see below). Once a trajectory reachesn_steps
, the environment is reset. If the environment wraps multiple environments together, the number of steps is tracked for each environment independently. Negative values are allowed, in which case this argument is ignored. Defaults toNone
(i.e., no maximum number of steps).init_random_frames (int, optional) – Number of frames for which the policy is ignored before it is called. This feature is mainly intended to be used in offline/model-based settings, where a batch of random trajectories can be used to initialize training. If provided, it will be rounded up to the closest multiple of frames_per_batch. Defaults to
None
(i.e. no random frames).reset_at_each_iter (bool, optional) – Whether environments should be reset at the beginning of a batch collection. Defaults to
False
.postproc (Callable, optional) – A post-processing transform, such as a
Transform
or aMultiStep
instance. Defaults toNone
.split_trajs (bool, optional) – Boolean indicating whether the resulting TensorDict should be split according to the trajectories. See
split_trajectories()
for more information. Defaults toFalse
.exploration_type (ExplorationType, optional) – interaction mode to be used when collecting data. Must be one of
torchrl.envs.utils.ExplorationType.RANDOM
,torchrl.envs.utils.ExplorationType.MODE
ortorchrl.envs.utils.ExplorationType.MEAN
. Defaults totorchrl.envs.utils.ExplorationType.RANDOM
.collector_class (type or str, optional) –
a collector class for the remote node. Can be
SyncDataCollector
,MultiSyncDataCollector
,MultiaSyncDataCollector
or a derived class of these. The strings “single”, “sync” and “async” correspond to respective class. Defaults toSyncDataCollector
.Note
Support for
MultiSyncDataCollector
andMultiaSyncDataCollector
is experimental, andSyncDataCollector
should always be preferred. If multiple simultaneous environment need to be executed on a single node, consider using aParallelEnv
instance.collector_kwargs (dict or list, optional) – a dictionary of parameters to be passed to the remote data-collector. If a list is provided, each element will correspond to an individual set of keyword arguments for the dedicated collector.
num_workers_per_collector (int, optional) – the number of copies of the env constructor that is to be used on the remote nodes. Defaults to 1 (a single env per collector). On a single worker node all the sub-workers will be executing the same environment. If different environments need to be executed, they should be dispatched across worker nodes, not subnodes.
sync (bool, optional) – if
True
, the resulting tensordict is a stack of all the tensordicts collected on each node. IfFalse
(default), each tensordict results from a separate node in a “first-ready, first-served” fashion.slurm_kwargs (dict) – a dictionary of parameters to be passed to the submitit executor.
update_after_each_batch (bool, optional) – if
True
, the weights will be updated after each collection. Forsync=True
, this means that all workers will see their weights updated. Forsync=False
, only the worker from which the data has been gathered will be updated. Defaults toFalse
, ie. updates have to be executed manually throughupdate_policy_weights_()
.max_weight_update_interval (int, optional) – the maximum number of batches that can be collected before the policy weights of a worker is updated. For sync collections, this parameter is overwritten by
update_after_each_batch
. For async collections, it may be that one worker has not seen its parameters being updated for a certain time even ifupdate_after_each_batch
is turned on. Defaults to -1 (no forced update).launcher (str, optional) – how jobs should be launched. Can be one of “submitit” or “mp” for multiprocessing. The former can launch jobs across multiple nodes, whilst the latter will only launch jobs on a single machine. “submitit” requires the homonymous library to be installed. To find more about submitit, visit https://github.com/facebookincubator/submitit Defaults to “submitit”.
tcp_port (int, optional) – the TCP port to be used. Defaults to 10003.
visible_devices (list of Union[int, torch.device, str], optional) – a list of the same length as the number of nodes containing the device used to pass data to main.
tensorpipe_options (dict, optional) – a dictionary of keyword argument to pass to
torch.distributed.rpc.TensorPipeRpcBackendOption
.
- update_policy_weights_(workers=None, wait=True) None [source]¶
Updates the policy weights if the policy of the data collector and the trained policy live on different devices.
- Parameters:
policy_weights (TensorDictBase, optional) – if provided, a TensorDict containing the weights of the policy to be used for the udpdate.