Shortcuts

Collector

class torchrl.collectors.Collector(create_env_fn: torchrl.envs.common.EnvBase | torchrl.envs.env_creator.EnvCreator | collections.abc.Sequence[collections.abc.Callable[[], torchrl.envs.common.EnvBase]], policy: None | tensordict.nn.common.TensorDictModule | collections.abc.Callable[[tensordict.base.TensorDictBase], tensordict.base.TensorDictBase] = None, *, policy_factory: collections.abc.Callable[[], collections.abc.Callable] | None = None, frames_per_batch: int, total_frames: int = - 1, device: Optional[Union[device, str, int]] = None, storing_device: Optional[Union[device, str, int]] = None, policy_device: Optional[Union[device, str, int]] = None, env_device: Optional[Union[device, str, int]] = None, create_env_kwargs: dict[str, Any] | None = None, max_frames_per_traj: int | None = None, init_random_frames: int | None = None, reset_at_each_iter: bool = False, postproc: collections.abc.Callable[[tensordict.base.TensorDictBase], tensordict.base.TensorDictBase] | None = None, split_trajs: bool | None = None, exploration_type: InteractionType = InteractionType.RANDOM, return_same_td: bool = False, reset_when_done: bool = True, interruptor=None, set_truncated: bool = False, use_buffers: bool | None = None, replay_buffer: torchrl.data.replay_buffers.replay_buffers.ReplayBuffer | None = None, extend_buffer: bool = True, local_init_rb: bool | None = None, trust_policy: bool | None = None, compile_policy: bool | dict[str, Any] | None = None, cudagraph_policy: bool | dict[str, Any] | None = None, no_cuda_sync: bool = False, weight_updater: torchrl.collectors.weight_update.WeightUpdaterBase | collections.abc.Callable[[], torchrl.collectors.weight_update.WeightUpdaterBase] | None = None, weight_sync_schemes: dict[str, torchrl.weight_update.weight_sync_schemes.WeightSyncScheme] | None = None, weight_recv_schemes: dict[str, torchrl.weight_update.weight_sync_schemes.WeightSyncScheme] | None = None, track_policy_version: bool = False, worker_idx: int | None = None, **kwargs)[source]

Generic data collector for RL problems. Requires an environment constructor and a policy.

Parameters:
  • create_env_fn (Callable or EnvBase) – a callable that returns an instance of EnvBase class, or the env itself.

  • policy (Callable) –

    Policy to be executed in the environment. Must accept tensordict.tensordict.TensorDictBase object as input. If None is provided, the policy used will be a RandomPolicy instance with the environment action_spec. Accepted policies are usually subclasses of TensorDictModuleBase. This is the recommended usage of the collector. Other callables are accepted too: If the policy is not a TensorDictModuleBase (e.g., a regular Module instances) it will be wrapped in a nn.Module first. Then, the collector will try to assess if these modules require wrapping in a TensorDictModule or not.

    • If the policy forward signature matches any of forward(self, tensordict), forward(self, td) or forward(self, <anything>: TensorDictBase) (or any typing with a single argument typed as a subclass of TensorDictBase) then the policy won’t be wrapped in a TensorDictModule.

    • 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).

    Note

    If the policy needs to be passed as a policy factory (e.g., in case it mustn’t be serialized / pickled directly), the policy_factory should be used instead.

Keyword Arguments:
  • policy_factory (Callable[[], Callable], optional) –

    a callable that returns a policy instance. This is exclusive with the policy argument.

    Note

    policy_factory comes in handy whenever the policy cannot be serialized.

  • 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 by frames_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: if device is not None and any of storing_device, policy_device or env_device is not specified, its value will be set to device. Defaults to None (No default device).

  • storing_device (int, str or torch.device, optional) – The device on which the output TensorDict will be stored. If device is passed and storing_device is None, it will default to the value indicated by device. 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 to None (the output tensordict isn’t on a specific device, leaf tensors sit on the device where they were created).

  • env_device (int, str or torch.device, optional) – The 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. If device is passed and env_device=None, it will default to device. If the value as such specified of env_device differs from policy_device and one of them is not None, the data will be cast to env_device before being passed to the env (i.e., passing different devices to policy and env is supported). Defaults to None.

  • policy_device (int, str or torch.device, optional) – The device on which the policy should be cast. If device is passed and policy_device=None, it will default to device. If the value as such specified of policy_device differs from env_device and one of them is not None, the data will be cast to policy_device before being passed to the policy (i.e., passing different devices to policy and env is supported). Defaults to None.

  • create_env_kwargs (dict, optional) – Dictionary of kwargs for create_env_fn.

  • 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 to True, see below). Once a trajectory reaches n_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 to None (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 a MultiStep instance.

    Warning

    Postproc is not applied when a replay buffer is used and items are added to the buffer as they are produced (extend_buffer=False). The recommended usage is to use extend_buffer=True.

    Defaults to None.

  • split_trajs (bool, optional) – Boolean indicating whether the resulting TensorDict should be split according to the trajectories. See split_trajectories() for more information. Defaults to False.

  • exploration_type (ExplorationType, optional) – interaction mode to be used when collecting data. Must be one of torchrl.envs.utils.ExplorationType.DETERMINISTIC, torchrl.envs.utils.ExplorationType.RANDOM, torchrl.envs.utils.ExplorationType.MODE or torchrl.envs.utils.ExplorationType.MEAN.

  • return_same_td (bool, optional) – if True, the same TensorDict will be returned at each iteration, with its values updated. This feature should be used cautiously: if the same tensordict is added to a replay buffer for instance, the whole content of the buffer will be identical. Default is False.

  • interruptor (_Interruptor, optional) – An _Interruptor object that can be used from outside the class to control rollout collection. The _Interruptor class has methods ´start_collection´ and ´stop_collection´, which allow to implement strategies such as preeptively stopping rollout collection. Default is False.

  • set_truncated (bool, optional) – if True, the truncated signals (and corresponding "done" but not "terminated") will be set to True when the last frame of a rollout is reached. If no "truncated" key is found, an exception is raised. Truncated keys can be set through env.add_truncated_keys. Defaults to False.

  • use_buffers (bool, optional) – if True, a buffer will be used to stack the data. This isn’t compatible with environments with dynamic specs. Defaults to True for envs without dynamic specs, False for others.

  • replay_buffer (ReplayBuffer, optional) –

    if provided, the collector will not yield tensordicts but populate the buffer instead. Defaults to None.

    See also

    By default (extend_buffer=True), the buffer is extended with entire rollouts. If the buffer needs to be populated with individual frames as they are collected, set extend_buffer=False (deprecated).

    Warning

    Using a replay buffer with a postproc or split_trajs=True requires extend_buffer=True, as the whole batch needs to be observed to apply these transforms.

  • extend_buffer (bool, optional) –

    if True, the replay buffer is extended with entire rollouts and not with single steps. Defaults to True.

    Note

    Setting this to False is deprecated and will be removed in a future version. Extending the buffer with entire rollouts is the recommended approach for better compatibility with postprocessing and trajectory splitting.

  • trust_policy (bool, optional) – if True, a non-TensorDictModule policy will be trusted to be assumed to be compatible with the collector. This defaults to True for CudaGraphModules and False otherwise.

  • compile_policy (bool or Dict[str, Any], optional) – if True, the policy will be compiled using compile() default behaviour. If a dictionary of kwargs is passed, it will be used to compile the policy.

  • cudagraph_policy (bool or Dict[str, Any], optional) – if True, the policy will be wrapped in CudaGraphModule with default kwargs. If a dictionary of kwargs is passed, it will be used to wrap the policy.

  • no_cuda_sync (bool) – if True, explicit CUDA synchronizations calls will be bypassed. For environments running directly on CUDA (IsaacLab or ManiSkills) cuda synchronization may cause unexpected crashes. Defaults to False.

  • weight_updater (WeightUpdaterBase or constructor, optional) – An instance of WeightUpdaterBase or its subclass, responsible for updating the policy weights on remote inference workers. This is typically not used in Collector as it operates in a single-process environment. Consider using a constructor if the updater needs to be serialized.

  • weight_sync_schemes (dict[str, WeightSyncScheme], optional) – Not supported for Collector. Collector is a leaf collector and cannot send weights to sub-collectors. Providing this parameter will raise a ValueError. Use weight_recv_schemes if you need to receive weights from a parent collector.

  • weight_recv_schemes (dict[str, WeightSyncScheme], optional) – Dictionary of weight sync schemes for RECEIVING weights from parent collectors. Keys are model identifiers (e.g., “policy”) and values are WeightSyncScheme instances configured to receive weights. This enables cascading weight updates in hierarchies like: RPCDataCollector -> MultiSyncCollector -> Collector. Defaults to None.

  • track_policy_version (bool or PolicyVersion, optional) – if True, the collector will track the version of the policy. This will be mediated by the PolicyVersion transform, which will be added to the environment. Alternatively, a PolicyVersion instance can be passed, which will be used to track the policy version. Defaults to False.

Examples

>>> from torchrl.envs.libs.gym import GymEnv
>>> from tensordict.nn import TensorDictModule
>>> from torch import nn
>>> env_maker = lambda: GymEnv("Pendulum-v1", device="cpu")
>>> policy = TensorDictModule(nn.Linear(3, 1), in_keys=["observation"], out_keys=["action"])
>>> collector = Collector(
...     create_env_fn=env_maker,
...     policy=policy,
...     total_frames=2000,
...     max_frames_per_traj=50,
...     frames_per_batch=200,
...     init_random_frames=-1,
...     reset_at_each_iter=False,
...     device="cpu",
...     storing_device="cpu",
... )
>>> for i, data in enumerate(collector):
...     if i == 2:
...         print(data)
...         break
TensorDict(
    fields={
        action: Tensor(shape=torch.Size([200, 1]), device=cpu, dtype=torch.float32, is_shared=False),
        collector: TensorDict(
            fields={
                traj_ids: Tensor(shape=torch.Size([200]), device=cpu, dtype=torch.int64, is_shared=False)},
            batch_size=torch.Size([200]),
            device=cpu,
            is_shared=False),
        done: Tensor(shape=torch.Size([200, 1]), device=cpu, dtype=torch.bool, is_shared=False),
        next: TensorDict(
            fields={
                done: Tensor(shape=torch.Size([200, 1]), device=cpu, dtype=torch.bool, is_shared=False),
                observation: Tensor(shape=torch.Size([200, 3]), device=cpu, dtype=torch.float32, is_shared=False),
                reward: Tensor(shape=torch.Size([200, 1]), device=cpu, dtype=torch.float32, is_shared=False),
                step_count: Tensor(shape=torch.Size([200, 1]), device=cpu, dtype=torch.int64, is_shared=False),
                truncated: Tensor(shape=torch.Size([200, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
            batch_size=torch.Size([200]),
            device=cpu,
            is_shared=False),
        observation: Tensor(shape=torch.Size([200, 3]), device=cpu, dtype=torch.float32, is_shared=False),
        step_count: Tensor(shape=torch.Size([200, 1]), device=cpu, dtype=torch.int64, is_shared=False),
        truncated: Tensor(shape=torch.Size([200, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
    batch_size=torch.Size([200]),
    device=cpu,
    is_shared=False)
>>> del collector

The collector delivers batches of data that are marked with a "time" dimension.

Examples

>>> assert data.names[-1] == "time"
async_shutdown(timeout: float | None = None, close_env: bool = True) None[source]

Finishes processes started by ray.init() during async execution.

cascade_execute(attr_path: str, *args, **kwargs) Any

Execute a method on a nested attribute of this collector.

This method allows remote callers to invoke methods on nested attributes of the collector without needing to know the full structure. It’s particularly useful for calling methods on weight sync schemes from the sender side.

Parameters:
  • attr_path – Full path to the callable, e.g., “_receiver_schemes[‘model_id’]._set_dist_connection_info”

  • *args – Positional arguments to pass to the method.

  • **kwargs – Keyword arguments to pass to the method.

Returns:

The return value of the method call.

Examples

>>> collector.cascade_execute(
...     "_receiver_schemes['policy']._set_dist_connection_info",
...     connection_info_ref,
...     worker_idx=0
... )
get_model(model_id: str)[source]

Get model instance by ID (for weight sync schemes).

Parameters:

model_id – Model identifier (e.g., “policy”, “value_net”)

Returns:

The model instance

Raises:

ValueError – If model_id is not recognized

get_policy_version() str | int | None[source]

Get the current policy version.

This method exists to support remote calls in Ray actors, since properties cannot be accessed directly through Ray’s RPC mechanism.

Returns:

The current version number (int) or UUID (str), or None if version tracking is disabled.

getattr_env(attr)[source]

Get an attribute from the environment.

getattr_policy(attr)[source]

Get an attribute from the policy.

getattr_rb(attr)[source]

Get an attribute from the replay buffer.

increment_version()[source]

Increment the policy version.

init_updater(*args, **kwargs)

Initialize the weight updater with custom arguments.

This method passes the arguments to the weight updater’s init method. If no weight updater is set, this is a no-op.

Parameters:
  • *args – Positional arguments for weight updater initialization

  • **kwargs – Keyword arguments for weight updater initialization

iterator() Iterator[TensorDictBase][source]

Iterates through the DataCollector.

Yields: TensorDictBase objects containing (chunks of) trajectories

load_state_dict(state_dict: OrderedDict, **kwargs) None[source]

Loads a state_dict on the environment and policy.

Parameters:

state_dict (OrderedDict) – ordered dictionary containing the fields “policy_state_dict” and "env_state_dict".

pause()

Context manager that pauses the collector if it is running free.

property policy_version: str | int | None

The current policy version.

receive_weights(policy_or_weights: tensordict.base.TensorDictBase | tensordict.nn.common.TensorDictModuleBase | torch.nn.modules.module.Module | dict | None = None, *, weights: tensordict.base.TensorDictBase | dict | None = None, policy: tensordict.nn.common.TensorDictModuleBase | torch.nn.modules.module.Module | None = None) None

Receive and apply weights to the collector’s policy.

This method applies weights to the local policy. When receiver schemes are registered, it delegates to those schemes. Otherwise, it directly applies the provided weights.

The method accepts weights in multiple forms for convenience:

Examples

>>> # Receive from registered schemes (distributed collectors)
>>> collector.receive_weights()
>>>
>>> # Apply weights from a policy module (positional)
>>> collector.receive_weights(trained_policy)
>>>
>>> # Apply weights from a TensorDict (positional)
>>> collector.receive_weights(weights_tensordict)
>>>
>>> # Use keyword arguments for clarity
>>> collector.receive_weights(weights=weights_td)
>>> collector.receive_weights(policy=trained_policy)
Parameters:

policy_or_weights

The weights to apply. Can be:

  • nn.Module: A policy module whose weights will be extracted and applied

  • TensorDictModuleBase: A TensorDict module whose weights will be extracted

  • TensorDictBase: A TensorDict containing weights

  • dict: A regular dict containing weights

  • None: Receive from registered schemes or mirror from original policy

Keyword Arguments:
  • weights – Alternative to positional argument. A TensorDict or dict containing weights to apply. Cannot be used together with policy_or_weights or policy.

  • policy – Alternative to positional argument. An nn.Module or TensorDictModuleBase whose weights will be extracted. Cannot be used together with policy_or_weights or weights.

Raises:

ValueError – If conflicting parameters are provided or if arguments are passed when receiver schemes are registered.

register_scheme_receiver(weight_recv_schemes: dict[str, torchrl.weight_update.weight_sync_schemes.WeightSyncScheme], *, synchronize_weights: bool = True)

Set up receiver schemes for this collector to receive weights from parent collectors.

This method initializes receiver schemes and stores them in _receiver_schemes for later use by _receive_weights_scheme() and receive_weights().

Receiver schemes enable cascading weight updates across collector hierarchies: - Parent collector sends weights via its weight_sync_schemes (senders) - Child collector receives weights via its weight_recv_schemes (receivers) - If child is also a parent (intermediate node), it can propagate to its own children

Parameters:

weight_recv_schemes (dict[str, WeightSyncScheme]) – Dictionary of {model_id: WeightSyncScheme} to set up as receivers. These schemes will receive weights from parent collectors.

Keyword Arguments:

synchronize_weights (bool, optional) – If True, synchronize weights immediately after registering the schemes. Defaults to True.

reset(index=None, **kwargs) None[source]

Resets the environments to a new initial state.

rollout() TensorDictBase[source]

Computes a rollout in the environment using the provided policy.

Returns:

TensorDictBase containing the computed rollout.

set_seed(seed: int, static_seed: bool = False) int[source]

Sets the seeds of the environments stored in the DataCollector.

Parameters:
  • seed (int) – integer representing the seed to be used for the environment.

  • static_seed (bool, optional) – if True, the seed is not incremented. Defaults to False

Returns:

Output seed. This is useful when more than one environment is contained in the DataCollector, as the seed will be incremented for each of these. The resulting seed is the seed of the last environment.

Examples

>>> from torchrl.envs import ParallelEnv
>>> from torchrl.envs.libs.gym import GymEnv
>>> from tensordict.nn import TensorDictModule
>>> from torch import nn
>>> env_fn = lambda: GymEnv("Pendulum-v1")
>>> env_fn_parallel = ParallelEnv(6, env_fn)
>>> policy = TensorDictModule(nn.Linear(3, 1), in_keys=["observation"], out_keys=["action"])
>>> collector = Collector(env_fn_parallel, policy, total_frames=300, frames_per_batch=100)
>>> out_seed = collector.set_seed(1)  # out_seed = 6
shutdown(timeout: float | None = None, close_env: bool = True, raise_on_error: bool = True) None[source]

Shuts down all workers and/or closes the local environment.

Parameters:
  • timeout (float, optional) – The timeout for closing pipes between workers. No effect for this class.

  • close_env (bool, optional) – Whether to close the environment. Defaults to True.

  • raise_on_error (bool, optional) – Whether to raise an error if the shutdown fails. Defaults to True.

start()[source]

Starts the collector in a separate thread for asynchronous data collection.

The collected data is stored in the provided replay buffer. This method is useful when you want to decouple data collection from training, allowing your training loop to run independently of the data collection process.

Raises:

RuntimeError – If no replay buffer is defined during the collector’s initialization.

Example

>>> from torchrl.modules import RandomPolicy            >>>             >>> import time
>>> from functools import partial
>>>
>>> import tqdm
>>>
>>> from torchrl.collectors import Collector
>>> from torchrl.data import LazyTensorStorage, ReplayBuffer
>>> from torchrl.envs import GymEnv, set_gym_backend
>>> import ale_py
>>>
>>> # Set the gym backend to gymnasium
>>> set_gym_backend("gymnasium").set()
>>>
>>> if __name__ == "__main__":
...     # Create a random policy for the Pong environment
...     env = GymEnv("ALE/Pong-v5")
...     policy = RandomPolicy(env.action_spec)
...
...     # Initialize a shared replay buffer
...     rb = ReplayBuffer(storage=LazyTensorStorage(1000), shared=True)
...
...     # Create a synchronous data collector
...     collector = Collector(
...         env,
...         policy=policy,
...         replay_buffer=rb,
...         frames_per_batch=256,
...         total_frames=-1,
...     )
...
...     # Progress bar to track the number of collected frames
...     pbar = tqdm.tqdm(total=100_000)
...
...     # Start the collector asynchronously
...     collector.start()
...
...     # Track the write count of the replay buffer
...     prec_wc = 0
...     while True:
...         wc = rb.write_count
...         c = wc - prec_wc
...         prec_wc = wc
...
...         # Update the progress bar
...         pbar.update(c)
...         pbar.set_description(f"Write Count: {rb.write_count}")
...
...         # Check the write count every 0.5 seconds
...         time.sleep(0.5)
...
...         # Stop when the desired number of frames is reached
...         if rb.write_count . 100_000:
...             break
...
...     # Shut down the collector
...     collector.async_shutdown()
state_dict() OrderedDict[source]

Returns the local state_dict of the data collector (environment and policy).

Returns:

an ordered dictionary with fields "policy_state_dict" and “env_state_dict”.

update_policy_weights_(policy_or_weights: tensordict.base.TensorDictBase | tensordict.nn.common.TensorDictModuleBase | dict | None = None, *, worker_ids: int | list[int] | torch.device | list[torch.device] | None = None, **kwargs) None[source]

Update policy weights for the data collector.

This method synchronizes the policy weights used by the collector with the latest trained weights. It supports both local and remote weight updates, depending on the collector configuration.

The method accepts weights in multiple forms for convenience:

Examples

>>> # Pass policy module as positional argument
>>> collector.update_policy_weights_(policy_module)
>>>
>>> # Pass TensorDict weights as positional argument
>>> collector.update_policy_weights_(weights_tensordict)
>>>
>>> # Use keyword arguments for clarity
>>> collector.update_policy_weights_(weights=weights_td, model_id="actor")
>>> collector.update_policy_weights_(policy=actor_module, model_id="actor")
>>>
>>> # Update multiple models atomically
>>> collector.update_policy_weights_(weights_dict={
...     "actor": actor_weights,
...     "critic": critic_weights,
... })
Parameters:

policy_or_weights

The weights to update with. Can be:

  • nn.Module: A policy module whose weights will be extracted

  • TensorDictModuleBase: A TensorDict module whose weights will be extracted

  • TensorDictBase: A TensorDict containing weights

  • dict: A regular dict containing weights

  • None: Will try to get weights from server using _get_server_weights()

Keyword Arguments:
  • weights – Alternative to positional argument. A TensorDict or dict containing weights to update. Cannot be used together with policy_or_weights or policy.

  • policy – Alternative to positional argument. An nn.Module or TensorDictModuleBase whose weights will be extracted. Cannot be used together with policy_or_weights or weights.

  • worker_ids – Identifiers for the workers to update. Relevant when the collector has multiple workers. Can be int, list of ints, device, or list of devices.

  • model_id – The model identifier to update (default: "policy"). Cannot be used together with weights_dict.

  • weights_dict – Dictionary mapping model_id to weights for updating multiple models atomically. Keys should match model_ids registered in weight_sync_schemes. Cannot be used together with model_id, policy_or_weights, weights, or policy.

Raises:
  • TypeError – If worker_ids is provided but no weight_updater is configured.

  • ValueError – If conflicting parameters are provided.

Note

Users should extend the WeightUpdaterBase classes to customize the weight update logic for specific use cases.

See also

LocalWeightsUpdaterBase and RemoteWeightsUpdaterBase().

property worker_idx: int | None

Get the worker index for this collector.

Returns:

The worker index (0-indexed).

Raises:

RuntimeError – If worker_idx has not been set.

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources