from_any#
- tensordict.from_any(obj, *, auto_batch_size: bool = False, batch_dims: int | None = None, device: device | None = None, batch_size: Size | None = None)#
Converts a dict, tuple, dataclass, array or file to a tensordict, recursively.
The conversion depends on the type of
obj: seeTensorDictBase.from_anyfor the list. A tensor or a tensor collection is returned as it is.- Parameters:
obj – the object 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. Exclusive withbatch_size, except for a dict, wherebatch_sizewins, and for anh5py.File, whereauto_batch_sizewins. Defaults toFalse.batch_dims (int, optional) – with
auto_batch_size, the maximum number of batch dimensions. Ignored withoutauto_batch_size, with aFutureWarningwhen it would change the result. Starting with TensorDict 0.17, the default will change to turning onauto_batch_sizewhenbatch_dimsis given, asfrom_dictdoes. 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. Exclusive with
auto_batch_size, except for a dict, wherebatch_sizewins and no batch size is computed, and for anh5py.File, whereauto_batch_sizewins andbatch_sizeis ignored. Defaults toNone.
- Returns:
A tensordict (a
PersistentTensorDictfor an HDF5 file), a tensor or aNonTensorStackfor a list, orobjitself for the other types.
Examples
>>> import torch >>> from tensordict import from_any >>> td = from_any({"obs": torch.zeros(3, 4), "pair": (torch.zeros(3), 1)}) >>> sorted(td.keys(include_nested=True, leaves_only=True), key=str) [('pair', '0'), ('pair', '1'), 'obs']