TensorDictBase.from_any#
- classmethod TensorDictBase.from_any(obj, *, auto_batch_size: bool = False, batch_dims: int | None = None, device: device | None = None, batch_size: Size | None = None)#
Recursively converts any object to a TensorDict.
Note
from_anyis less restrictive than the regular TensorDict constructor. It can cast data structures like dataclasses or tuples to a tensordict using custom heuristics. This approach may incur some extra overhead and involves more opinionated choices in terms of mapping strategies.Note
This method recursively converts the input object to a TensorDict. If the object is already a TensorDict (or any similar tensor collection object), it will be returned as is.
- Parameters:
obj – The object to be converted.
- Keyword Arguments:
auto_batch_size (bool, optional) – if
True, the batch size will be computed automatically. Defaults toFalse.batch_dims (int, optional) – If auto_batch_size is
True, defines how many dimensions the output tensordict should have. Defaults toNone(full batch-size at each level).device (device, optional) – The device on which the TensorDict will be created.
batch_size (Size, optional) – The batch size of the TensorDict. Exclusive with
auto_batch_size.
- Returns:
A TensorDict representation of the input object.
Supported objects:
Dataclasses through
from_dataclass()(dataclasses will be converted to TensorDict instances, not tensorclasses).Namedtuples through
from_namedtuple().Dictionaries through
from_dict().Tuples through
from_tuple(). This includes the results oftorch.return_types(max,sort,topk, …), which get the keys"0","1", … and aFutureWarning. Starting with TensorDict 0.17, the default will change to their field names ("values","indices", …), asfrom_namedtuple()gives.NumPy’s structured arrays through
from_struct_array().HDF5 objects through
from_h5().
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.