TensorDictBase.from_dict_instance#
- TensorDictBase.from_dict_instance(input_dict, *, auto_batch_size: bool | None = None, batch_size=None, device=None, batch_dims=None, names=None)#
Builds a tensordict from a dictionary, with the types of the entries of this tensordict.
Works like
from_dict(), except for the nested dicts: a nested dict whose key is a nested tensordict or tensorclass of this tensordict is converted to that type, recursively. The other nested dicts becomeTensorDictinstances. Use it to turn the output ofto_dict()back into tensorclasses. The values of this tensordict are not used, and the result is aTensorDict.- Parameters:
input_dict (dict) – the dictionary to convert. Nested dicts become nested entries.
- Keyword Arguments:
auto_batch_size (bool, optional) – if
True, sets the batch size to the largest leading shape that all the entries share. Defaults toNone, which behaves likeFalseunlessbatch_dimsis given.batch_size (Size or list of int, optional) – the batch size of the result: the leading dimensions that all its entries share. Defaults to
None, which gives an empty batch size unless the batch size is computed.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_dims (int, optional) – with
auto_batch_size, the maximum number of batch dimensions. Turns onauto_batch_sizewhen that isNone. Exclusive withbatch_size. Defaults toNone.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.
- Raises:
ValueError – if both
batch_sizeandbatch_dimsare given.
Examples
>>> import torch >>> from tensordict import TensorDict, tensorclass >>> @tensorclass ... class MyClass: ... x: torch.Tensor >>> td = TensorDict(a=torch.zeros(()), b=MyClass(x=torch.zeros(()))) >>> data = {"a": torch.ones(()), "b": {"x": torch.ones(())}} >>> type(td.from_dict_instance(data)["b"]).__name__ 'MyClass' >>> type(TensorDict.from_dict(data)["b"]).__name__ 'TensorDict'
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.