Rate this Page
★ ★ ★ ★ ★

from_dict#

tensordict.from_dict(d, *, auto_batch_size: bool | None = None, batch_dims: int | None = None, device: device | None = None, batch_size: Size | None = None, names: Sequence[str] | None = None) → TensorDictBase#

Converts a dictionary to a tensordict, recursively.

Nested dicts become nested tensordicts, and the values are converted with from_any(). Unlike the TensorDict constructor, it can compute the batch size. See TensorDict.from_dict.

Parameters:

d (dict) – the dictionary to convert.

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

  • batch_dims (int, optional) – with auto_batch_size, the maximum number of batch dimensions. Turns on auto_batch_size when that is None. Exclusive with batch_size. 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_size (Size or list of int, optional) – the batch size of the result: the leading dimensions that all its entries share. Takes precedence over auto_batch_size. Defaults to None, an empty batch size unless it is computed.

  • names (list of str, optional) – the names of the batch dimensions, one per dimension. Used only with batch_size: when the batch size is empty or computed, the names are dropped. Defaults to None.

Returns:

A TensorDict.

Raises:

ValueError – if both batch_size and batch_dims are given.

Examples

>>> import torch
>>> from tensordict import from_dict
>>> input_dict = {"a": torch.zeros(3, 4), "b": {"c": torch.zeros(3, 4, 5)}}
>>> from_dict(input_dict).batch_size
torch.Size([])
>>> td = from_dict(input_dict, auto_batch_size=True)
>>> td.batch_size, td["b"].batch_size
(torch.Size([3, 4]), torch.Size([3, 4, 5]))
>>> from_dict(input_dict, batch_dims=1).batch_size
torch.Size([3])
>>> from_dict(input_dict, batch_size=[3], names=["n"]).names
['n']