Rate this Page
★ ★ ★ ★ ★

TensorDictBase.to_tensordict#

TensorDictBase.to_tensordict(*, retain_none: bool | None = None) → Self#

Returns a TensorDict copy of this tensordict.

Every tensor is cloned, and every sub-tensordict and tensorclass is converted to a TensorDict, recursively. Use it to get a regular, unlocked tensordict in memory from a lazy stack, a memory-mapped or locked tensordict, a PersistentTensorDict or a tensorclass. The batch size, device and dimension names are kept, with one exception: if the tensordicts of a lazy stack have no names, the result has no names either, even when the stack dimension has a name (from stack_dim_name or the names setter). densify() and clone() of the lazy stack keep that name. To keep it here, name the dimension again with refine_names().

Keyword Arguments:

retain_none (bool, optional) – if True, the None fields of tensorclass instances are written as entries of the result. Defaults to None, which behaves like False: the None fields are dropped.

Returns:

a new TensorDict object containing the same values.

Examples

>>> import torch
>>> from tensordict import LazyStackedTensorDict, TensorDict
>>> stack = LazyStackedTensorDict(
...     TensorDict(a=torch.zeros(3)), TensorDict(a=torch.ones(3)), stack_dim=0)
>>> td = stack.to_tensordict()
>>> type(td).__name__, td.batch_size
('TensorDict', torch.Size([2]))
>>> stack.names = ["s"]
>>> stack.to_tensordict().names
[None]
>>> stack.to_tensordict().refine_names("s").names
['s']

Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.