Rate this Page
★ ★ ★ ★ ★

TensorDictBase.from_list#

classmethod TensorDictBase.from_list(input, *, auto_batch_size: bool | None = None, batch_size: Size | None = None, device: device | None = None, batch_dims: int | None = None, names: list[str] | None = None, lazy: bool | None = None) → Self#

Builds a tensordict by stacking a list of dicts or tensor collections.

Each dict is converted with from_dict() and the results are stacked along a new leading dimension. A tensordict or tensorclass in the list is stacked as it is: the keyword arguments do not apply to it. When the result does not get the batch_size or device asked for, a FutureWarning is emitted: starting with TensorDict 0.17, the default will change to applying them to the result, which raises if the batch size does not fit, as for a list of dicts.

Parameters:

input (list) – the dicts or tensor collections to stack.

Keyword Arguments:
  • auto_batch_size (bool, optional) – if True, sets the batch size of each element to the largest leading shape that all its entries share. Defaults to None, which behaves like False unless batch_dims is given.

  • batch_size (Size or list of int, optional) – the batch size of the result, with the length of the list first. Each element gets batch_size[1:]. Defaults to None.

  • device (device, str or int, optional) – the device of the result. Leaves on another device are moved to it. None leaves each leaf where it is, and the result has no device. Defaults to None.

  • batch_dims (int, optional) – the maximum number of batch dimensions of the result, the list dimension included. Turns on auto_batch_size when that is None. Exclusive with batch_size. Defaults to None.

  • names (list of str, optional) – the names of the batch dimensions of the result, one per dimension, with the name of the list dimension first. Defaults to None.

  • lazy (bool, optional) – if True, the result is a lazy stack; if False, a dense stack. Defaults to None, which builds a dense stack when the elements have the same shape and a lazy stack otherwise. See Stacking and variable-size data.

Raises:

ValueError – if batch_size[0] is not the length of the list.

Examples

>>> import torch
>>> from tensordict import TensorDict
>>> td = TensorDict.from_list(
...     [{"a": torch.zeros(3)}, {"a": torch.zeros(3)}],
...     batch_size=[2, 3],
...     names=["x", "y"],
... )
>>> td.batch_size
torch.Size([2, 3])
>>> td.names
['x', 'y']

Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.