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 theTensorDictconstructor, it can compute the batch size. SeeTensorDict.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 toNone, which behaves likeFalseunlessbatch_dimsis given.batch_dims (int, optional) – with
auto_batch_size, the maximum number of batch dimensions. Turns onauto_batch_sizewhen that isNone. Exclusive withbatch_size. Defaults toNone.device (device, str or int, optional) – the device of the result. Leaves on another device are moved to it.
Noneleaves each leaf where it is, and the result has no device. Defaults toNone.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 toNone, 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 toNone.
- Returns:
A
TensorDict.- Raises:
ValueError – if both
batch_sizeandbatch_dimsare 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']