Data Structures and Utilities¶
This module provides essential data structures and utility functions for handling experiences and datasets in reinforcement learning.
The main components include the Transition tensorclass for representing environment transitions, the ReplayDataset for
creating iterable datasets from replay buffers, and utility functions for converting between different data formats.
The Transition class wraps observations, actions, rewards, next observations, and done flags as a structured data container,
automatically handling conversions between different data types and formats. The ReplayDataset enables integration with
PyTorch’s DataLoader for distributed training scenarios.
from agilerl.components.data import Transition, ReplayDataset, to_tensordict
from agilerl.components.replay_buffer import ReplayBuffer
# Create a transition
transition = Transition(
obs=obs,
action=action,
reward=reward,
next_obs=next_obs,
done=done
)
# Create a dataset from a replay buffer
buffer = ReplayBuffer(max_size=10000, device=device)
dataset = ReplayDataset(buffer, batch_size=32)
Functions¶
- agilerl.components.data.to_tensordict(data: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | dict[str, ndarray[tuple[int, ...], dtype[_ScalarType_co]]] | tuple[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ...] | Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor] | Number | list[RolloutPrompt] | RolloutPrompt, dtype: dtype = torch.float32) TensorDict¶
Convert a tuple or dict of torch.Tensor or np.ndarray to a TensorDict.
- Parameters:
data (ObservationType) – Tuple or dict of torch.Tensor or np.ndarray.
dtype (torch.dtype, optional) – Data type of the TensorDict, defaults to torch.float32
- Returns:
TensorDict, whether the data was a tuple or not.
- agilerl.components.data.to_torch_tensor(data: object, dtype: dtype = torch.float32) Tensor¶
Convert a numpy array, torch tensor, Python number, or other array-like :param data: Numpy array, torch tensor, Python number, or other array-like. :type data: object :param dtype: Data type of the torch tensor, defaults to torch.float32 :type dtype: torch.dtype, optional :return: Torch tensor.
Classes¶
- class agilerl.components.data.Transition(obs: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | dict[str, ndarray[tuple[int, ...], dtype[_ScalarType_co]]] | tuple[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ...] | Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor] | Number | list[RolloutPrompt] | RolloutPrompt, action: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor, next_obs: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | dict[str, ndarray[tuple[int, ...], dtype[_ScalarType_co]]] | tuple[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ...] | Tensor | TensorDict | tuple[Tensor, ...] | dict[str, Tensor] | Number | list[RolloutPrompt] | RolloutPrompt, reward: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor | SupportsFloat, done: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor | SupportsFloat, *, batch_size, device=None, names=None)¶
One environment step staged for a
ReplayBuffer.- cat(dim: int = 0, *, out=None)¶
Concatenates tensordicts into a single tensordict along the given dimension.
This call is equivalent to calling
torch.cat()but is compatible with torch.compile. The tensordicts must have the same keys, and the same batch size except alongdim.- Args:
input (sequence of TensorDictBase): the tensordicts to concatenate. dim (int, optional): the batch dimension to concatenate along.
Defaults to
0.- Keyword Args:
- out (TensorDictBase, optional): a tensordict to write the result
into.
- Examples:
>>> import torch >>> from tensordict import TensorDict >>> a = TensorDict(x=torch.zeros(3), batch_size=[3]) >>> b = TensorDict(x=torch.ones(3), batch_size=[3]) >>> TensorDict.cat([a, b]).batch_size torch.Size([6])
- property device: torch.device¶
Retrieves the device type of tensor class.
- dumps(prefix: str | None = None, copy_existing: bool = False, *, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False, robust_key: bool | None = True, archive: bool | None = None, compression: str | int | None = None) Self¶
Saves the tensordict to disk, and returns a memory-mapped copy of it.
save(and its aliasdumps) ismemmap(): it takes the same arguments.selfis not changed. Read the result back withload(). See saving.- Args:
- prefix (str or Path): the directory where the tensordict is
written, one file per leaf. If
prefixends with".tdz"orarchive=True, a single archive file is written instead.
- Keyword Args:
- archive (bool, optional): if
True, write a single archive file. Defaults to
None, which writes an archive ifprefixends with".tdz".- compression (str or int, optional): the compression of the
archive. See
memmap().
- archive (bool, optional): if
All the other arguments are those of
memmap().- Examples:
>>> import tempfile >>> import torch >>> from tensordict import TensorDict >>> td = TensorDict(a=torch.zeros(3), nested=TensorDict(b=torch.ones(3), batch_size=[3]), batch_size=[3]) >>> with tempfile.TemporaryDirectory() as path: ... _ = td.save(path) ... loaded = TensorDict.load(path) ... print((loaded == td).all()) True
- extend(tensordict: list[TensorDictBase] | TensorDictBase) None¶
Appends tensordicts to the lazy stack that the instance holds.
Deprecated since version 0.15: Build a new instance with
tensordict.lazy_stack()ortorch.cat()instead.
- classmethod fields() tuple[dataclasses.Field, ...]¶
Returns the fields of the tensorclass.
Deprecated since version 0.15: Use
dataclasses.fields(cls)instead. It returns the same tuple ofdataclasses.Fieldobjects.
- from_any(*, auto_batch_size: bool = False, batch_dims: int | None = None, device: torch.device | None = None, batch_size: torch.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.
- Args:
obj: The object to be converted.
- Keyword Args:
- auto_batch_size (bool, optional): if
True, the batch size will be computed automatically. Defaults to
False.- batch_dims (int, optional): If auto_batch_size is
True, defines how many dimensions the output tensordict should have. Defaults to
None(full batch-size at each level).
device (torch.device, optional): The device on which the TensorDict will be created. batch_size (torch.Size, optional): The batch size of the TensorDict.
Exclusive with
auto_batch_size.- auto_batch_size (bool, optional): if
- 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().
- from_consolidated()¶
Reconstructs a tensordict from a file written by
consolidate().The batch sizes and names are as they were when the file was written. To write later changes into the file, call
consolidate(filename=filename)again on the consolidated tensordict. Seefrom_consolidated().
- from_csv(*, auto_batch_size: bool = False, batch_dims: int | None = None, device: torch.device | None = None, batch_size: torch.Size | None = None, separator: str | None = None, dtype: torch.dtype | None = None, **kwargs) Self¶
Creates a TensorDict from a CSV file.
Requires either pandas or pyarrow to be installed.
- Args:
path (str or Path): Path to the CSV file.
- Keyword Args:
- auto_batch_size (bool, optional): If
True, the batch size will be computed automatically. Defaults to
False.- batch_dims (int, optional): If
auto_batch_sizeisTrue, defines how many dimensions the output tensordict should have. Defaults to
None.- device (torch.device, optional): The device for tensor data.
Defaults to
None.- batch_size (torch.Size, optional): The batch size. Defaults to
[num_rows].- separator (str, optional): If provided, column names are split on
this separator to create nested TensorDicts. Defaults to
None.- dtype (torch.dtype, optional): If provided, all numeric columns
are cast to this dtype. Defaults to
None.- **kwargs: Additional keyword arguments forwarded to the CSV reader
(
pandas.read_csvorpyarrow.csv.read_csv).
- auto_batch_size (bool, optional): If
- Returns:
A TensorDict representation of the CSV data.
- Examples:
>>> import os >>> import tempfile >>> import torch >>> from tensordict import TensorDict >>> data = TensorDict(obs=torch.arange(3.0), reward=torch.ones(3), batch_size=[3]) >>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.csv") ... data.to_csv(path) ... td = TensorDict.from_csv(path) ... td32 = TensorDict.from_csv(path, dtype=torch.float32) >>> td.batch_size, td["obs"].dtype, td32["obs"].dtype (torch.Size([3]), torch.float64, torch.float32)
- from_dataclass(*, dest_cls: Type | None = None, auto_batch_size: bool = False, batch_dims: int | None = None, as_tensorclass: bool = False, device: torch.device | None = None, batch_size: torch.Size | None = None)¶
Converts a dataclass into a TensorDict instance.
- Args:
dataclass: The dataclass instance to be converted.
- Keyword Args:
- dest_cls (tensorclass, optional): A tensorclass type to be used to map the data. If not provided, a new
class is created. Without effect if
objis a type or as_tensorclass is False.- auto_batch_size (bool, optional): If
True, automatically determines and applies batch size to the resulting TensorDict. Defaults to
False.- batch_dims (int, optional): If
auto_batch_sizeisTrue, defines how many dimensions the output tensordict should have. Defaults to
None(full batch-size at each level).- as_tensorclass (bool, optional): If
True, delegates the conversion to the free function from_dataclass()and returns a tensor-compatible class (tensorclass()) or instance instead of a TensorDict. Defaults toFalse.- device (torch.device, optional): The device on which the TensorDict will be created.
Defaults to
None.- batch_size (torch.Size, optional): The batch size of the TensorDict.
Defaults to
None.
- Returns:
A TensorDict instance derived from the provided dataclass, unless as_tensorclass is True, in which case a tensor-compatible class or instance is returned.
- Raises:
TypeError: If the provided input is not a dataclass instance.
Warning
This method is distinct from the free function from_dataclass and serves a different purpose. While the free function returns a tensor-compatible class or instance, this method returns a TensorDict instance.
Note
This method creates a new TensorDict instance with keys corresponding to the fields of the input dataclass.
Each key in the resulting TensorDict is initialized using the cls.from_any method.
The auto_batch_size option allows for automatic batch size determination and application to the resulting TensorDict.
- classmethod from_dict(input_dict, *, auto_batch_size: bool | None = None, batch_size=None, device=None, batch_dims=None)¶
Builds an instance of the tensorclass from a dictionary of its fields.
The fields that
input_dictmisses are set toNone, also those that declare a default or a default factory. Starting with TensorDict 0.17, the default will change to filling these fields with their defaults, as the constructor does. Until then, a call that misses such a field warns with aFutureWarning.- Args:
- input_dict (dict): the values of the fields. Nested dictionaries become
tensordicts, or tensorclasses for the fields annotated with one.
- Keyword Args:
auto_batch_size (bool, optional): whether to infer the batch size. batch_size (torch.Size, optional): the batch size. device (torch.device, optional): the device. batch_dims (int, optional): the number of batch dimensions to infer.
- from_h5(*, mode: str = 'r', auto_batch_size: bool = False, batch_dims: int | None = None, batch_size: torch.Size | None = None, non_tensor_as_stack: bool = False)¶
Creates a PersistentTensorDict from a h5 file.
- Args:
filename (str): The path to the h5 file.
- Keyword Arguments:
- mode (str, optional): how the file is opened:
"r"(read only), "r+"(read and write), or another mode ofh5py.File(seePersistentTensorDict). Defaults to"r".- auto_batch_size (bool, optional): If
True, the batch size will be computed automatically. Defaults to
False.- batch_dims (int, optional): If auto_batch_size is
True, defines how many dimensions the output tensordict should have. Defaults to
None(full batch-size at each level).
batch_size (torch.Size, optional): The batch size of the TensorDict. Defaults to
None. non_tensor_as_stack (bool, optional): ifTrue, a non-tensordataset that tensordict did not write, such as a string column with one string per row, reads as a
NonTensorStackof its rows when its leading dims equal the batch size. Otherwise it reads as oneNonTensorDatathat holds the whole dataset. Defaults toFalse.- mode (str, optional): how the file is opened:
- Returns:
A PersistentTensorDict representation of the input h5 file.
- Examples:
>>> import os >>> import tempfile >>> import torch >>> from tensordict import TensorDict >>> data = TensorDict(key1=torch.zeros(3), key2=torch.ones(3), batch_size=[3]) >>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "file.h5") ... _ = data.to_h5(path) ... td = TensorDict.from_h5(path) ... print(td) PersistentTensorDict( fields={ key1: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), key2: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)
- from_json(*, auto_batch_size: bool = False, batch_dims: int | None = None, device: torch.device | None = None, batch_size: torch.Size | None = None, separator: str | None = None, dtype: torch.dtype | None = None, lines: bool = False, **kwargs) Self¶
Creates a TensorDict from a JSON file.
Supports both standard JSON (array of records) and JSON Lines format. For nested JSON objects, use
from_dict()instead.Requires pandas for best results. Falls back to stdlib
jsonfor simple cases.- Args:
path (str or Path): Path to the JSON file.
- Keyword Args:
- auto_batch_size (bool, optional): If
True, the batch size will be computed automatically. Defaults to
False.- batch_dims (int, optional): If
auto_batch_sizeisTrue, defines how many dimensions the output tensordict should have. Defaults to
None.- device (torch.device, optional): The device for tensor data.
Defaults to
None.- batch_size (torch.Size, optional): The batch size. Defaults to
[num_rows].- separator (str, optional): If provided, column names are split on
this separator to create nested TensorDicts. Defaults to
None.- dtype (torch.dtype, optional): If provided, all numeric columns
are cast to this dtype. Defaults to
None.- lines (bool, optional): If
True, reads the file as JSON Lines (one JSON object per line). Defaults to
False.- **kwargs: Additional keyword arguments forwarded to the JSON
reader.
- auto_batch_size (bool, optional): If
- Returns:
A TensorDict representation of the JSON data.
- Examples:
>>> import os >>> import tempfile >>> import torch >>> from tensordict import TensorDict >>> data = TensorDict(obs=torch.arange(3.0), reward=torch.ones(3), batch_size=[3]) >>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.json") ... data.to_json(path) ... td = TensorDict.from_json(path) ... path_lines = os.path.join(tmpdir, "data.jsonl") ... data.to_json(path_lines, lines=True) ... td_lines = TensorDict.from_json(path_lines, lines=True) >>> td.batch_size, td_lines.batch_size (torch.Size([3]), torch.Size([3]))
- from_list(*, auto_batch_size: bool | None = None, batch_size: torch.Size | None = None, device: torch.device | None = None, batch_dims: int | None = None, names: list[str] | None = None, lazy: bool | None = None) Self¶
Builds a tensordict by stacking a list of dicts or tensor collections.
Each dict is converted with
from_dict()and the results are stacked along a new leading dimension.- Args:
input (list): the dicts or tensor collections to stack.
- Keyword Args:
- auto_batch_size (bool, optional): if
True, the batch size of each element is computed automatically. See
from_dict().- batch_size (iterable of int, optional): the batch size of the
result, with the length of the list first. Each element gets
batch_size[1:].- device (torch.device or compatible type, optional): a device for
the result.
- batch_dims (int, optional): the maximum number of batch dimensions
of the result, the list dimension included. Exclusive with
batch_size.- names (list of str, optional): the dimension names of the result,
one per batch dimension, with the name of the list dimension first.
- lazy (bool, optional): if
True, the result is a lazy stack; if
False, a dense stack. Defaults toNone, which builds a dense stack when the elements have the same shape and a lazy stack otherwise.
- auto_batch_size (bool, optional): if
- Examples:
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict.from_list( ... [{"a": torch.zeros(3)}, {"a": torch.zeros(3)}], ... batch_size=[2, 3], ... names=["x", "y"], ... ) >>> td.batch_size torch.Size([2, 3]) >>> td.names ['x', 'y']
- from_module(as_module: bool = False, lock: bool = False, use_state_dict: bool = False, filter_empty: bool = True)¶
Puts the parameters and buffers of a module in a tensordict.
The entries are the parameters and buffers of the module themselves, not copies. Submodules become nested tensordicts.
Note
This method does not lock the result by default (
lock=False). The functiontensordict.from_module()locks it by default (lock=True).- Args:
module (nn.Module): the module to get the parameters from. as_module (bool, optional): if
True, aTensorDictParamsinstance is returned, which can be used to store parameters within a
torch.nn.Module. Defaults toFalse.- lock (bool, optional): if
True, the resulting tensordict is locked. Defaults to
False.- use_state_dict (bool, optional): if
True, the state-dict from the module is used and unflattened into a TensorDict with the tree structure of the model. Use it when the module has state-dict hooks. Defaults to
False.- filter_empty (bool, optional): if
True, submodules without parameters or buffers (
nn.ReLU, for example) get no entry. IfFalse, they get an empty tensordict. Defaults toTrue.
- lock (bool, optional): if
- Returns:
a
TensorDict, or aTensorDictParamsifas_module=True.- Examples:
>>> from torch import nn >>> from tensordict import TensorDict >>> module = nn.Sequential(nn.Linear(3, 4), nn.ReLU()) >>> params = TensorDict.from_module(module) >>> params["0", "weight"] is module[0].weight True >>> list(params.keys()) ['0'] >>> params.is_locked False
- from_modules(*, as_module: bool = False, lock: bool = True, use_state_dict: bool = False, lazy_stack: bool = False, expand_identical: bool = False)¶
Retrieves the parameters of several modules for ensebmle learning/feature of expects applications through vmap.
- Args:
- modules (sequence of nn.Module): the modules to get the parameters from.
If the modules differ in their structure, a lazy stack is needed (see the
lazy_stackargument below).
- Keyword Args:
- as_module (bool, optional): if
True, aTensorDictParams instance will be returned which can be used to store parameters within a
torch.nn.Module. Defaults toFalse.- lock (bool, optional): if
True, the resulting tensordict will be locked. Defaults to
True.- use_state_dict (bool, optional): if
True, the state-dict from the module will be used and unflattened into a TensorDict with the tree structure of the model. Defaults to
False.Note
This is particularly useful when state-dict hooks have to be used.
- lazy_stack (bool, optional): whether parameters should be densly or
lazily stacked. Defaults to
False(dense stack).Note
lazy_stackandas_moduleare exclusive features.Warning
There is a crucial difference between lazy and non-lazy outputs in that non-lazy output will reinstantiate parameters with the desired batch-size, while
lazy_stackwill just represent the parameters as lazily stacked. This means that whilst the original parameters can safely be passed to an optimizer whenlazy_stack=True, the new parameters need to be passed when it is set toTrue.Warning
Whilst it can be tempting to use a lazy stack to keep the orignal parameter references, remember that lazy stack perform a stack each time
get()is called. This will require memory (N times the size of the parameters, more if a graph is built) and time to be computed. It also means that the optimizer(s) will contain more parameters, and operations likestep()orzero_grad()will take longer to be executed. In general,lazy_stackshould be reserved to very few use cases.- expand_identical (bool, optional): if
Trueand the same parameter (same identity) is being stacked to itself, an expanded version of this parameter will be returned instead. This argument is ignored when
lazy_stack=True.
- as_module (bool, optional): if
- Examples:
>>> import torch >>> from torch import nn >>> from tensordict import TensorDict >>> _ = torch.manual_seed(0) >>> empty_module = nn.Linear(3, 4, device="meta") >>> n_models = 2 >>> modules = [nn.Linear(3, 4) for _ in range(n_models)] >>> params = TensorDict.from_modules(*modules) >>> print(params) TensorDict( fields={ bias: Parameter(shape=torch.Size([2, 4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Parameter(shape=torch.Size([2, 4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([2]), device=None, is_shared=False) >>> # example of batch execution >>> def exec_module(params, x): ... with params.to_module(empty_module): ... return empty_module(x) >>> x = torch.randn(3) >>> y = torch.vmap(exec_module, (0, None))(params, x) >>> assert y.shape == (n_models, 4) >>> # since lazy_stack = False, backprop leaves the original params untouched >>> y.sum().backward() >>> assert params["weight"].grad.norm() > 0 >>> assert modules[0].weight.grad is None
With
lazy_stack=True, things are slightly different:>>> params = TensorDict.from_modules(*modules, lazy_stack=True) >>> print(params) LazyStackedTensorDict( fields={ bias: Tensor(shape=torch.Size([2, 4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Tensor(shape=torch.Size([2, 4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, exclusive_fields={ }, batch_size=torch.Size([2]), device=None, is_shared=False, stack_dim=0) >>> # example of batch execution >>> y = torch.vmap(exec_module, (0, None))(params, x) >>> assert y.shape == (n_models, 4) >>> y.sum().backward() >>> assert modules[0].weight.grad is not None
- from_namedtuple(*, auto_batch_size: bool = False, batch_dims: int | None = None, device: torch.device | None = None, batch_size: torch.Size | None = None)¶
Converts a namedtuple to a TensorDict recursively.
- Args:
named_tuple: The namedtuple instance to be converted.
- Keyword Args:
- auto_batch_size (bool, optional): if
True, the batch size will be computed automatically. Defaults to
False.- batch_dims (int, optional): If
auto_batch_sizeisTrue, defines how many dimensions the output tensordict should have. Defaults to
None(full batch-size at each level).- device (torch.device, optional): The device on which the TensorDict will be created.
Defaults to
None.- batch_size (torch.Size, optional): The batch size of the TensorDict.
Defaults to
None.
- auto_batch_size (bool, optional): if
- Returns:
A TensorDict representation of the input namedtuple.
- Examples:
>>> from tensordict import TensorDict >>> import torch >>> data = TensorDict({ ... "a_tensor": torch.zeros((3)), ... "nested": {"a_tensor": torch.zeros((3)), "a_string": "zero!"}}, [3]) >>> nt = data.to_namedtuple() >>> print(nt) GenericDict(a_tensor=tensor([0., 0., 0.]), nested=GenericDict(a_tensor=tensor([0., 0., 0.]), a_string='zero!')) >>> TensorDict.from_namedtuple(nt, auto_batch_size=True) TensorDict( fields={ a_tensor: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), nested: TensorDict( fields={ a_string: NonTensorData(data=zero!, batch_size=torch.Size([3]), device=None), a_tensor: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)
- from_pandas(*, auto_batch_size: bool = False, batch_dims: int | None = None, device: torch.device | None = None, batch_size: torch.Size | None = None, separator: str | None = None, dtype: torch.dtype | None = None) Self¶
Converts a pandas DataFrame to a TensorDict.
Numeric columns become tensors, string/object columns become
NonTensorData.- Args:
dataframe (pd.DataFrame): The pandas DataFrame to convert.
- Keyword Args:
- auto_batch_size (bool, optional): If
True, the batch size will be computed automatically. Defaults to
False.- batch_dims (int, optional): If
auto_batch_sizeisTrue, defines how many dimensions the output tensordict should have. Defaults to
None.- device (torch.device, optional): The device for tensor data.
Defaults to
None.- batch_size (torch.Size, optional): The batch size. Defaults to
[num_rows].- separator (str, optional): If provided, column names are split on
this separator to create nested TensorDicts. For example, with
separator=".", a column"obs.x"becomestd["obs", "x"]. Defaults toNone.- dtype (torch.dtype, optional): If provided, all numeric columns
are cast to this dtype. Defaults to
None.
- auto_batch_size (bool, optional): If
- Returns:
A TensorDict representation of the DataFrame.
- Examples:
>>> from tensordict import TensorDict >>> import pandas as pd >>> df = pd.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]}) >>> td = TensorDict.from_pandas(df) >>> print(td) TensorDict( fields={ a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.int64, is_shared=False), b: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float64, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)
- from_parquet(*, auto_batch_size: bool = False, batch_dims: int | None = None, device: torch.device | None = None, batch_size: torch.Size | None = None, separator: str | None = None, dtype: torch.dtype | None = None, columns: list[str] | None = None, **kwargs) Self¶
Creates a TensorDict from a Parquet file.
Requires either pyarrow or pandas to be installed. Prefers pyarrow when available for better performance.
- Args:
path (str or Path): Path to the Parquet file.
- Keyword Args:
- auto_batch_size (bool, optional): If
True, the batch size will be computed automatically. Defaults to
False.- batch_dims (int, optional): If
auto_batch_sizeisTrue, defines how many dimensions the output tensordict should have. Defaults to
None.- device (torch.device, optional): The device for tensor data.
Defaults to
None.- batch_size (torch.Size, optional): The batch size. Defaults to
[num_rows].- separator (str, optional): If provided, column names are split on
this separator to create nested TensorDicts. Defaults to
None.- dtype (torch.dtype, optional): If provided, all numeric columns
are cast to this dtype. Defaults to
None.- columns (list of str, optional): If provided, only read these
columns from the file. Defaults to
None(all columns).- **kwargs: Additional keyword arguments forwarded to the Parquet
reader.
- auto_batch_size (bool, optional): If
- Returns:
A TensorDict representation of the Parquet data.
- Examples:
>>> import os >>> import tempfile >>> import torch >>> from tensordict import TensorDict >>> data = TensorDict(obs=torch.arange(3.0), reward=torch.ones(3), batch_size=[3]) >>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.parquet") ... data.to_parquet(path) ... td = TensorDict.from_parquet(path) ... td_obs = TensorDict.from_parquet(path, columns=["obs"]) >>> sorted(td.keys()), sorted(td_obs.keys()) (['obs', 'reward'], ['obs'])
- from_pytree(*, batch_size: torch.Size | None = None, auto_batch_size: bool = False, batch_dims: int | None = None)¶
Converts a pytree to a TensorDict instance.
This method is designed to keep the pytree nested structure as much as possible.
Additional non-tensor keys are added to keep track of each level’s identity, providing a built-in pytree-to-tensordict bijective transform API.
Accepted classes currently include lists, tuples, named tuples and dict, and subclasses of these such as
collections.OrderedDict,collections.defaultdictand the results oftorch.maxand the othertorch.return_types. Adefaultdictis rebuilt without itsdefault_factory.Note
For dictionaries, non-NestedKey keys are registered separately as
NonTensorDatainstances.Note
Tensor-castable types (such as int, float or np.ndarray) will be converted to torch.Tensor instances. Note that this transformation is surjective: transforming back the tensordict to a pytree will not recover the original types.
Note
The list fields of a named tuple, and some of its dict and tuple fields, are converted with
from_any()and do not round-trip throughto_pytree():a list of numbers comes back as a tensor;
a dict holding a str, list or tuple, and an empty dict or named tuple (or a dict or named tuple holding one), come back as a
GenericDictnamed tuple;a tuple subclass, such as a
torch.return_typesresult, and a plain tuple holding anything but tensors, Python ints and floats, dicts and named tuples (such as a str, a list or a NumPy number), or holding one of the dicts or named tuples above, maketo_pytree()raise aValueError, and an empty tuple comes back as an emptyGenericDict.
The other dict, named tuple and plain tuple fields come back with their own type.
- Examples:
>>> import torch >>> from tensordict import TensorDict >>> # Create a pytree with tensor leaves, and one "weird"-looking dict key >>> class WeirdLookingClass: ... pass ... >>> weird_key = WeirdLookingClass() >>> # Make a pytree with tuple, lists, dict and namedtuple >>> pytree = ( ... [torch.randint(10, (3,)), torch.zeros(2)], ... { ... "tensor": torch.randn( ... 2, ... ), ... "td": TensorDict({"one": 1}), ... weird_key: torch.randint(10, (2,)), ... "list": [1, 2, 3], ... }, ... {"named_tuple": TensorDict({"two": torch.ones(1) * 2}).to_namedtuple()}, ... ) >>> # Build a TensorDict from that pytree >>> td = TensorDict.from_pytree(pytree) >>> # Recover the pytree >>> pytree_recon = td.to_pytree() >>> # Check that the leaves match >>> def check(v1, v2): ... assert (v1 == v2).all() ... >>> _ = torch.utils._pytree.tree_map(check, pytree, pytree_recon) >>> assert weird_key in pytree_recon[1]
- from_schema(*, batch_size: Sequence[int] | torch.Size | None = None, storage: str | None = None, device=None, **kwargs) TensorDictBase¶
Pre-allocate a zero-filled TensorDict from a schema.
Creates a
TensorDictBasewhose storage backend is selected bystorage. Each entry inschemamaps a field name to an(element_shape, dtype)pair; the full stored shape is[*batch_size, *element_shape].- Args:
- schema: Mapping from field name to
(element_shape, dtype). element_shapeis the per-element shape (excludingbatch_size).
- schema: Mapping from field name to
- Keyword Args:
- batch_size: Overall batch dimensions prepended to every element
shape. Defaults to
().
storage (str or None): Backend selector:
None– plainTensorDictwith regular tensors."memmap"– memory-mapped tensors on disk. Passprefix=<dir>in kwargs."h5"– HDF5 viaPersistentTensorDict. Passfilename=<path>in kwargs."zarr"– zarr (requireszarr>=3.0) viaPersistentTensorDict. Passfilename=<path or store>in kwargs."shared"– CPU shared-memory tensors."redis"/"dragonfly"– delegates toTensorDictStore.from_schema().
- device: Device for the resulting tensors (ignored by some
backends).
- **kwargs: Backend-specific arguments forwarded to the
underlying constructor (e.g.
prefixfor memmap,filenamefor h5,host/portfor redis).
- Returns:
A new
TensorDictBasesubclass instance with pre-allocated (zero-filled) keys.- Examples:
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict.from_schema( ... {"obs": ([84, 84, 3], torch.uint8), ... "reward": ([], torch.float32)}, ... batch_size=[1000], ... ) >>> td["obs"].shape torch.Size([1000, 84, 84, 3])
>>> import tempfile >>> with tempfile.TemporaryDirectory() as d: ... td_mm = TensorDict.from_schema( ... {"obs": ([4], torch.float32)}, ... batch_size=[8], ... storage="memmap", ... prefix=d, ... ) ... assert td_mm.is_memmap()
- from_struct_array(*, auto_batch_size: bool = False, batch_dims: int | None = None, device: torch.device | None = None, batch_size: torch.Size | None = None) Self¶
Converts a structured numpy array to a TensorDict.
The resulting TensorDict will share the same memory content as the numpy array (it is a zero-copy operation). Changing values of the structured numpy array in-place will affect the content of the TensorDict.
Note
This method performs a zero-copy operation, meaning that the resulting TensorDict will share the same memory content as the input numpy array. Therefore, changing values of the numpy array in-place will affect the content of the TensorDict. The exception is a field whose item size does not divide the size of a record, such as the
"i8"field of a packed array of"i8"and"f4"fields (12 bytes per record): torch cannot view such a field, so it is copied.- Args:
struct_array (np.ndarray): The structured numpy array to be converted.
- Keyword Args:
auto_batch_size (bool, optional): If
True, the batch size will be computed automatically. Defaults toFalse. batch_dims (int, optional): Ifauto_batch_sizeisTrue, defines how many dimensions the outputtensordict should have. Defaults to
None(full batch-size at each level).- device (torch.device, optional): The device on which the TensorDict will be created.
Defaults to
None.Note
Changing the device (i.e., specifying any device other than
Noneor"cpu") will transfer the data, resulting in a change to the memory location of the returned data.
batch_size (torch.Size, optional): The batch size of the TensorDict. Defaults to None.
- Returns:
A TensorDict representation of the input structured numpy array.
- Examples:
>>> import numpy as np >>> from tensordict import TensorDict >>> x = np.array( ... [("Rex", 9, 81.0), ("Fido", 3, 27.0)], ... dtype=[("name", "U10"), ("age", "i4"), ("weight", "f4")], ... ) >>> td = TensorDict.from_struct_array(x) >>> x_recon = td.to_struct_array() >>> assert (x_recon == x).all() >>> assert x_recon.shape == x.shape >>> # Try modifying x age field and check effect on td >>> x["age"] += 1 >>> assert (td["age"] == np.array([10, 4])).all()
- classmethod from_tensordict(tensordict: TensorDictBase, non_tensordict: dict | None = None, safe: bool | None = None) Self¶
Wraps a tensordict in a new instance of the tensorclass, without copying the leaves.
If
tensordictis aTensorDict, the entries of the fields annotated with a tensorclass (orOptionalof one) that are tensordicts become instances of that tensorclass, recursively. They are set in a shallow copy oftensordict, which keeps its own entries. An entry with keys that the annotated class does not declare stays a tensordict. Other backends are wrapped as they are: setting a tensorclass in them would write to their storage (e.g. an H5 file).- Args:
tensordict (TensorDictBase): the tensordict that holds the tensor fields. non_tensordict (dict, optional): the values of the non-tensor fields. The
fields that neither argument holds are set to
None.- safe (bool, optional): Deprecated in 0.15, to be removed in TensorDict 0.17. Whether to
raise an error if
tensordictis not aTensorDictBase. Without it, such a tensordict raises an error.
- Examples:
>>> import torch >>> from tensordict import TensorClass >>> class Pose(TensorClass): ... q: torch.Tensor >>> class Obs(TensorClass): ... a: Pose >>> obs = Obs(a=Pose(q=torch.zeros(5, 4), batch_size=[5]), batch_size=[5]) >>> type(Obs.from_tensordict(obs.to_tensordict()).a).__name__ 'Pose'
- from_tuple(*, auto_batch_size: bool = False, batch_dims: int | None = None, device: torch.device | None = None, batch_size: torch.Size | None = None)¶
Converts a tuple to a TensorDict.
- Args:
obj: The tuple instance to be converted.
- Keyword Args:
auto_batch_size (bool, optional): If
True, the batch size will be computed automatically. Defaults toFalse. batch_dims (int, optional): If auto_batch_size isTrue, defines how many dimensions the output tensordictshould have. Defaults to
None(full batch-size at each level).device (torch.device, optional): The device on which the TensorDict will be created. Defaults to
None. batch_size (torch.Size, optional): The batch size of the TensorDict. Defaults toNone.- Returns:
A TensorDict representation of the input tuple.
- Examples:
>>> from tensordict import TensorDict >>> my_tuple = (1, 2, 3) >>> td = TensorDict.from_tuple(my_tuple) >>> print(td) TensorDict( fields={ 0: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), 1: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), 2: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
- from_zarr(*, mode: str = 'r', auto_batch_size: bool = False, batch_dims: int | None = None, batch_size: torch.Size | None = None, non_tensor_as_stack: bool = False)¶
Creates a PersistentTensorDict from a zarr store.
Requires
zarr>=3.0to be installed.- Args:
- filename (str, path or zarr store): The path to the zarr store (a
directory), or a
zarr.abc.store.Storeinstance (e.g. azarr.storage.ZipStore).
- Keyword Arguments:
mode (str, optional): Reading mode. Defaults to
"r". auto_batch_size (bool, optional): IfTrue, the batch size will be computed automatically.Defaults to
False.- batch_dims (int, optional): If auto_batch_size is
True, defines how many dimensions the output tensordict should have. Defaults to
None(full batch-size at each level).- batch_size (torch.Size, optional): The batch size of the TensorDict. Defaults to
None (read from the metadata written by
to_zarr(), or automatically determined for stores written by other tools).- non_tensor_as_stack (bool, optional): if
True, a non-tensor array that tensordict did not write, such as a string column with one string per row, reads as a
NonTensorStackof its rows when its leading dims equal the batch size. Otherwise it reads as oneNonTensorDatathat holds the whole array. Defaults toFalse.
- batch_dims (int, optional): If auto_batch_size is
- Returns:
A PersistentTensorDict representation of the input zarr store.
- Examples:
>>> import os >>> import tempfile >>> import torch >>> from tensordict import TensorDict >>> data = TensorDict(key1=torch.zeros(3), key2=torch.ones(3), batch_size=[3]) >>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "store.zarr") ... _ = data.to_zarr(path) ... td = TensorDict.from_zarr(path) ... print(td) PersistentTensorDict( fields={ key1: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), key2: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)
- fromkeys(value: Any = 0)¶
Creates a tensordict from a list of keys and a single value.
- Args:
keys (list of NestedKey): An iterable specifying the keys of the new dictionary. value (compatible type, optional): The value for all keys. Defaults to
0.
- get(key: NestedKey, *args, **kwargs)¶
Gets the value stored with the input key.
- Args:
- key (str, tuple of str): key to be queried. If tuple of str it is
equivalent to chained calls of getattr.
default: default value if the key is not found in the tensorclass.
- Returns:
value stored with the input key
- lazy_stack(dim: int = 0, *, out=None, **kwargs)¶
Creates a lazy stack of tensordicts.
A lazy stack keeps the tensordicts as they are and stacks their values only when you read them. The tensordicts can have different keys and different feature shapes. See stacking, and
tensordict.lazy_stack()for the arguments.- Examples:
>>> import torch >>> from tensordict import TensorDict >>> a = TensorDict(x=torch.zeros(3), batch_size=[3]) >>> b = TensorDict(y=torch.ones(3), batch_size=[3]) >>> stack = TensorDict.lazy_stack([a, b]) >>> type(stack).__name__, stack.batch_size ('LazyStackedTensorDict', torch.Size([2, 3]))
- load(*args, **kwargs) Self¶
Loads a tensordict that
save()ormemmap()wrote to disk.loadisload_memmap(): it takes the same arguments, includingallow_pickle,deviceandmode. The leaves of the result are memory-mapped tensors that read the files. See saving and the example ofsave().- Args:
- prefix (str or Path): the directory, or the
".tdz"archive file, to read.
- prefix (str or Path): the directory, or the
- load_(prefix: str | Path, *args, **kwargs)¶
Loads a tensordict from disk within the current tensordict.
This method is a proxy to
load_memmap_().Deprecated since version 0.15: Use
load_memmap_()instead.
- load_memmap(device: torch.device | None = None, non_blocking: bool = False, *, out: TensorDictBase | None = None, robust_key: bool | None = True, subpath: NestedKey | None = None, mode: str | None = None, num_threads: int = 0, allow_pickle: bool | None = None) Self¶
Loads a memory-mapped tensordict from disk.
- Args:
- prefix (str or Path to folder): the path to the folder where the
saved tensordict should be fetched, or the path to a memmap archive file written through
save(..., archive=True)/ a".tdz"prefix (or packed withpack_memmap()). Archives are memory-mapped once and every leaf is exposed as a zero-copy view into the mapping: only the pages of the leaves that are actually accessed are read from disk. Unlike directory-backed tensordicts, in-place writes to the leaves of an archive-loaded tensordict do not propagate to the file by default (seemode).- device (torch.device or equivalent, optional): if provided, the
data will be asynchronously cast to that device. Supports “meta” device, in which case the data isn’t loaded but a set of empty “meta” tensors are created. This is useful to get a sense of the total model size and structure without actually opening any file.
- non_blocking (bool, optional): if
True, synchronize won’t be called after loading tensors on device. Defaults to
False.- out (TensorDictBase, optional): optional tensordict where the data
should be loaded. Its nested containers are reused, but its leaves are rebound to the loaded tensors, so their storage is not reused. Keys of
outthat are missing from the saved data are removed. Ifouthas a device, the data is loaded on it, and a differentdeviceraises aValueError. To write the data into the preallocated storage ofout, useout.update_(TensorDict.load_memmap(prefix, device=device))instead.- robust_key (bool, optional): if
True(default), expects robust key encoding was used when saving and decodes filenames accordingly. If
False, uses legacy behavior. IfNone, uses the default robust behavior.- subpath (NestedKey or str path, optional): the location of a
nested tensordict to load, as a nested key (e.g.
("module", "0"), with arbitrary nesting allowed as usual) or as a"/"-separated string path (e.g."module/0"). Only that subtree is loaded. Works both for directories (equivalent to appending the path toprefix) and for archives. A nested key reaches the entries of a saved tensorclass asobj.get(key)does, without its_tensordictlevel.- mode (str, optional): how the files are memory-mapped. With
"r", the mapping is copy-on-write: in-place writes to the leaves stay in memory. They reach the files only if the tensordict is saved there, andmemmap_()without a prefix does not write back toprefix. With"r+", the mapping is shared: in-place writes propagate to the files, and a file that is not writable raises aPermissionError. Defaults toNone, which maps archives as with"r", and each file of a directory as with"r+"if the process can write it, as with"r"otherwise. Prefer"r"for data that is only read: on some network file systems (e.g. Lustre), page faults on a shared writable mapping take write locks, so readers on different nodes block each other. On Linux, copy-on-write mappings count against the memory commit limit, so a file larger than the available RAM and swap can fail to map with"r". With archives,"r+"requires uncompressed, aligned tensor payloads (i.e. archives written by tensordict withoutcompression) and is not available for nested-tensor leaves. In-place writes do not update the per-entry CRC-32 stored by the zip format;load_memmap()ignores checksums, but callrefresh_archive_checksums()before handing a modified archive to tools that verify them (unzip,unpack_memmap(), …).- num_threads (int, optional): number of threads used to decompress
the leaves of a compressed archive (deflate entries are inflated in parallel, which scales nearly linearly). Without compression, loading is a metadata-only operation and this argument has no effect. Defaults to
0(sequential).- allow_pickle (bool, optional): whether pickled non-tensor fields
may be loaded. Pickle can execute arbitrary code, so pass
Trueonly for data from a trusted source andFalsefor untrusted data. In TensorDict 0.14 and 0.15, omitting this option loads pickle with aFutureWarning; the default will change toFalsein 0.16. Saves without a pickle sidecar do not require this option.
- Examples:
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict.fromkeys(["a", "b", "c", ("nested", "e")], 0) >>> _ = td.memmap("./saved_td") >>> td_load = TensorDict.load_memmap("./saved_td") >>> assert (td == td_load).all()
This method also allows loading nested tensordicts.
- Examples:
>>> nested = TensorDict.load_memmap("./saved_td/nested") >>> assert nested["e"] == 0
A tensordict can also be loaded on “meta” device or, alternatively, as a fake tensor.
- Examples:
>>> import tempfile >>> td = TensorDict({"a": torch.zeros(()), "b": {"c": torch.zeros(())}}) >>> with tempfile.TemporaryDirectory() as path: ... _ = td.save(path) ... td_load = TensorDict.load_memmap(path, device="meta") ... print("meta:", td_load) ... from torch._subclasses import FakeTensorMode ... with FakeTensorMode(): ... td_load = TensorDict.load_memmap(path) ... print("fake:", td_load) meta: TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=meta, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=meta, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=meta, is_shared=False)}, batch_size=torch.Size([]), device=meta, is_shared=False) fake: TensorDict( fields={ a: FakeTensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: FakeTensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=cpu, is_shared=False)}, batch_size=torch.Size([]), device=cpu, is_shared=False)
- load_memmap_(prefix: str | Path, robust_key: bool | None = True, *, allow_pickle: bool | None = None, mode: str | None = None)¶
Loads the content of a memory-mapped tensorclass within the tensorclass where
load_memmap_is called.See
load_memmap_()for more info.
- load_state_dict(state_dict: dict[str, Any], strict=True, assign=False, from_flatten=None)¶
Loads a state_dict into the tensorclass.
Supports both the new format (logical keys with
_metadata) and the legacy format (_tensordict/_non_tensordictwrapper keys).
- maybe_dense_stack(dim: int = 0, *, out=None, **kwargs)¶
Attempts to make a dense stack of tensordicts, and falls back on lazy stack when required.
The result is a
TensorDictif the tensordicts have the same keys and shapes, and aLazyStackedTensorDictotherwise. See stacking, andtensordict.maybe_dense_stack()for the arguments.- Examples:
>>> import torch >>> from tensordict import TensorDict >>> a = TensorDict(x=torch.zeros(3), batch_size=[3]) >>> b = TensorDict(x=torch.ones(3), batch_size=[3]) >>> c = TensorDict(y=torch.ones(3), batch_size=[3]) >>> type(TensorDict.maybe_dense_stack([a, b])).__name__ 'TensorDict' >>> type(TensorDict.maybe_dense_stack([a, c])).__name__ 'LazyStackedTensorDict'
- memmap(prefix: str | None = None, copy_existing: bool = False, *, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False, existsok: bool = True, robust_key: bool | None = True, archive: bool | None = None, compression: str | int | None = None) Self¶
Writes all tensors onto a corresponding memory-mapped Tensor in a new tensordict.
- Args:
- prefix (str): directory prefix where the memory-mapped tensors will
be stored. The directory tree structure will mimic the tensordict’s. If
prefixends with".tdz"(orarchive=Trueis passed), a single-file archive is written instead of a directory: a standard zip file whose entries replicate the memmap directory layout. Seearchivebelow.- copy_existing (bool): If False (default), an exception will be raised if an
entry in the tensordict is already a tensor stored on disk with an associated file, but is not saved in the correct location according to prefix. If
True, any existing Tensor will be copied to the new location.
- Keyword Args:
- num_threads (int, optional): the number of threads used to write the memmap
tensors. Defaults to 0.
- return_early (bool, optional): if
Trueandnum_threads>0, the method will return a future of the tensordict.
- share_non_tensor (bool, optional): if
True, the non-tensor data will be shared between the processes and writing operation (such as inplace update or set) on any of the workers within a single node will update the value on all other workers. If the number of non_tensor leaves is high (e.g., sharing large stacks of non-tensor data) this may result in OOM or similar errors. Defaults to
False.- existsok (bool, optional): if
False, an exception will be raised if a tensor already exists in the same path. Defaults to
True.- robust_key (bool, optional): if
True(default), uses robust key encoding that safely handles keys with path separators and special characters. If
False, uses legacy behavior (keys used as-is). IfNone, uses the default robust behavior.- archive (bool, optional): if
True,prefixdesignates a single file rather than a directory and the tensordict is written as a memmap archive: a zip file mirroring the memmap directory tree, with tensor payloads stored uncompressed and aligned so that
load_memmap()can memory-map the file and expose every leaf as a zero-copy view. IfNone(default), archive mode is enabled whenprefixends with".tdz". The result ofload_memmap()on an archive behaves like the result offrom_consolidated(): all leaves are views into a single storage, and in-place writes do not propagate to the file. Archives and memmap directories are mutually convertible withpack_memmap()/unpack_memmap()(or any zip tool). Note that archives are written sequentially (single data pass) andnum_threadshas no effect on them. An existing archive is replaced by a new file rather than rewritten in place: a symlink is followed, but other hard links to the old file keep the old contents.- compression (str or int, optional): compression for archive
entries (
"stored","deflate","bzip2","lzma"or azipfileconstant). Defaults to"stored"(uncompressed), which is what enables zero-copy loading. Compressed archives load correctly but leaves are decompressed in memory on access. Only valid in archive mode.
The TensorDict is then locked, meaning that any writing operations that isn’t in-place will throw an exception (eg, rename, set or remove an entry). Once the tensordict is unlocked, the memory-mapped attribute is turned to
False, because cross-process identity is not guaranteed anymore.- Returns:
A new tensordict with the tensors stored on disk if
return_early=False, otherwise aTensorDictFutureinstance.- Note:
Serialising in this fashion might be slow with deeply nested tensordicts, so it is not recommended to call this method inside a training loop.
- memmap_(prefix: str | None = None, copy_existing: bool = False, *, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False, existsok: bool = True, robust_key: bool | None = True) Self¶
Writes all tensors onto a corresponding memory-mapped Tensor, in-place.
- Args:
- prefix (str): directory prefix where the memory-mapped tensors will
be stored. The directory tree structure will mimic the tensordict’s.
- copy_existing (bool): If False (default), an exception will be raised if an
entry in the tensordict is already a tensor stored on disk with an associated file, but is not saved in the correct location according to prefix. If
True, any existing Tensor will be copied to the new location.
- Keyword Args:
- num_threads (int, optional): the number of threads used to write the memmap
tensors. Defaults to 0.
- return_early (bool, optional): if
Trueandnum_threads>0, the method will return a future of the tensordict. The resulting tensordict can be queried using future.result().
- share_non_tensor (bool, optional): if
True, the non-tensor data will be shared between the processes and writing operation (such as inplace update or set) on any of the workers within a single node will update the value on all other workers. If the number of non-tensor leaves is high (e.g., sharing large stacks of non-tensor data) this may result in OOM or similar errors. Defaults to
False.- existsok (bool, optional): if
False, an exception will be raised if a tensor already exists in the same path. Defaults to
True.- robust_key (bool, optional): if
True(default), uses robust key encoding that safely handles keys with path separators and special characters. If
False, uses legacy behavior (keys used as-is). IfNone, uses the default robust behavior.
The TensorDict is then locked, meaning that any writing operations that isn’t in-place will throw an exception (eg, rename, set or remove an entry). Once the tensordict is unlocked, the memory-mapped attribute is turned to
False, because cross-process identity is not guaranteed anymore.- Returns:
self if
return_early=False, otherwise aTensorDictFutureinstance.- Note:
Serialising in this fashion might be slow with deeply nested tensordicts, so it is not recommended to call this method inside a training loop.
- Note:
A
PersistentTensorDict, aTensorDictStoreor aLazyStackedTensorDictStore(or one of its elements) cannot be memory-mapped in-place: this method raises aRuntimeError. Usememmap()to build a memory-mapped copy instead.
- memmap_like(prefix: str | None = None, copy_existing: bool = False, *, existsok: bool = True, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False, robust_key: bool | None = True, archive: bool | None = None) Self¶
Creates a memory-mapped tensordict with the same keys, shapes and dtypes, without copying the values.
The files are filled with zeros. Write the values into the result afterwards, for example with
update_()or indexing.- Args:
- prefix (str): directory prefix where the memory-mapped tensors will
be stored. The directory tree structure will mimic the tensordict’s. If
prefixends with".tdz"(orarchive=Trueis passed), a preallocated single-file archive is created instead. Seearchivebelow.- copy_existing (bool): If False (default), an exception will be raised if an
entry in the tensordict is already a tensor stored on disk with an associated file, but is not saved in the correct location according to prefix. If
True, any existing Tensor will be copied to the new location.
- Keyword Args:
- num_threads (int, optional): the number of threads used to write the memmap
tensors. Defaults to 0.
- return_early (bool, optional): if
Trueandnum_threads>0, the method will return a future of the tensordict.
- share_non_tensor (bool, optional): if
True, the non-tensor data will be shared between the processes and writing operation (such as inplace update or set) on any of the workers within a single node will update the value on all other workers. If the number of non-tensor leaves is high (e.g., sharing large stacks of non-tensor data) this may result in OOM or similar errors. Defaults to
False.- existsok (bool, optional): if
False, an exception will be raised if a tensor already exists in the same path. Defaults to
True.- robust_key (bool, optional): if
True(default), uses robust key encoding that safely handles keys with path separators and special characters. If
False, uses legacy behavior (keys used as-is). IfNone, uses the default robust behavior.- archive (bool, optional): if
True,prefixdesignates a single file and a preallocated, zero-filled memmap archive is created and loaded back with
load_memmap(prefix, mode="r+"): the returned tensordict writes through to the archive. IfNone(default), archive mode is enabled whenprefixends with".tdz". In-place writes leave the zip per-entry checksums stale; callrefresh_archive_checksums()before handing the archive to tools that verify them. Nested tensors are not supported in this mode.
The TensorDict is then locked, meaning that any writing operations that isn’t in-place will throw an exception (eg, rename, set or remove an entry). Once the tensordict is unlocked, the memory-mapped attribute is turned to
False, because cross-process identity is not guaranteed anymore.- Returns:
A new
TensorDictinstance with data stored as memory-mapped tensors ifreturn_early=False, otherwise aTensorDictFutureinstance.
Note
This is the recommended method to write a set of large buffers on disk, as
memmap_()will copy the information, which can be slow for large content.- Examples:
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict({ ... "a": torch.zeros((3, 64, 64), dtype=torch.uint8), ... "b": torch.zeros(1, dtype=torch.int64), ... }, batch_size=[]).expand(1_000) # expand does not allocate new memory >>> import tempfile >>> with tempfile.TemporaryDirectory() as path: ... buffer = td.memmap_like(path) ... print(buffer.is_memmap(), buffer["a"].shape) True torch.Size([1000, 3, 64, 64])
- memmap_refresh_(*, allow_pickle: bool | None = None)¶
Refreshes the content of the memory-mapped tensordict if it has a
saved_path.This method will raise an exception if no path is associated with it.
- Args:
- allow_pickle (bool, optional): whether pickled non-tensor fields
may be loaded. See
load_memmap().
- pack(dim: int = -1, *, layout: PackLayout | None = None) tuple[torch.Tensor, PackLayout]¶
Packs all the leaves of a tensordict into one tensor of features.
Each leaf is flattened after the batch dimensions, and the leaves are concatenated in the order of
keys(True, True, sort=True), so the columns depend on the set of keys only. Leaves can have different ranks. The result has shape(*batch_size, F)fordim=-1, whereFis the sum of the numbers of features of the leaves, and it is contiguous for anydim.PackLayout.unpackinverts it.Packing along the last dim copies the data once, with one
torch.cat(). Along another dim the result can take a second copy:torch.cat()keeps the channels-last strides that moving the feature dim gives a 4-d or 5-d result, and the result is then made contiguous.All the leaves must share one dtype and one device. Non-tensor data cannot be packed: drop it with
filter_non_tensor_data()first. A lazy stack packs like its dense equivalent if all its members have the same keys and feature shapes.- Args:
- dim (int, optional): the position of the packed dimension in the
result, in
[-(batch_dims + 1), batch_dims]as fortorch.stack(). Defaults to-1.
- Keyword Args:
- layout (PackLayout, optional): a layout to pack into. The columns
then follow its key order, and a missing, extra or reshaped leaf raises.
dimmust match the layout’s dim.
- Returns:
the packed tensor and its
PackLayout.- Examples:
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict( ... p=torch.zeros(5), ... v=torch.ones(5, 3), ... nested={"stress": torch.ones(5, 3, 3)}, ... batch_size=[5], ... ) >>> flat, layout = td.pack() >>> flat.shape torch.Size([5, 13]) >>> layout.keys (('nested', 'stress'), 'p', 'v') >>> out = layout.unpack(flat.index_select(0, torch.tensor([0, 2]))) >>> out.batch_size torch.Size([2]) >>> flat2, _ = td.pack(layout=layout) >>> assert (flat2 == flat).all()
- save(prefix: str | None = None, copy_existing: bool = False, *, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False, robust_key: bool | None = True, archive: bool | None = None, compression: str | int | None = None) Self¶
Saves the tensordict to disk, and returns a memory-mapped copy of it.
save(and its aliasdumps) ismemmap(): it takes the same arguments.selfis not changed. Read the result back withload(). See saving.- Args:
- prefix (str or Path): the directory where the tensordict is
written, one file per leaf. If
prefixends with".tdz"orarchive=True, a single archive file is written instead.
- Keyword Args:
- archive (bool, optional): if
True, write a single archive file. Defaults to
None, which writes an archive ifprefixends with".tdz".- compression (str or int, optional): the compression of the
archive. See
memmap().
- archive (bool, optional): if
All the other arguments are those of
memmap().- Examples:
>>> import tempfile >>> import torch >>> from tensordict import TensorDict >>> td = TensorDict(a=torch.zeros(3), nested=TensorDict(b=torch.ones(3), batch_size=[3]), batch_size=[3]) >>> with tempfile.TemporaryDirectory() as path: ... _ = td.save(path) ... loaded = TensorDict.load(path) ... print((loaded == td).all()) True
- select(*keys, inplace: bool = False, strict: bool = True, as_tensordict: bool = False)¶
TensorClass-specific select that supports
as_tensordict.
- set(key: NestedKey, value: Any, inplace: bool = False, non_blocking: bool = False)¶
Sets a new key-value pair.
- Args:
- key (str, tuple of str): name of the key to be set.
If tuple of str it is equivalent to chained calls of getattr followed by a final setattr.
value (Any): value to be stored in the tensorclass inplace (bool, optional): if
True, set will tentatively try toupdate the value in-place. If
Falseor if the key isn’t present, the value will be simply written at its destination.- Returns:
self
- stack(dim: int = 0, *, out=None)¶
Stacks tensordicts into a single tensordict along the given dimension.
This call is equivalent to calling
torch.stack()but is compatible with torch.compile. The tensordicts must have the same batch size and the same keys. Otherwise, the call raisesRuntimeError. To stack tensordicts with different keys or shapes, uselazy_stack(). See stacking.- Args:
input (sequence of TensorDictBase): the tensordicts to stack. dim (int, optional): the new batch dimension. Defaults to
0.- Keyword Args:
- out (TensorDictBase, optional): a tensordict to write the result
into.
- Examples:
>>> import torch >>> from tensordict import TensorDict >>> a = TensorDict(x=torch.zeros(3), batch_size=[3]) >>> b = TensorDict(x=torch.ones(3), batch_size=[3]) >>> TensorDict.stack([a, b]).batch_size torch.Size([2, 3])
- state_dict(destination=None, prefix='', keep_vars=False, flatten=True) dict[str, Any]¶
Returns a state_dict with logical keys, matching TensorDictBase conventions.
Tensor fields appear as data keys. Non-tensor fields (strings, ints, etc.) and the tensorclass type are stored in
_metadata. This replaces the legacy_tensordict/_non_tensordictwrapper format.
- to_tensordict(*, retain_none: bool | None = None) TensorDict¶
Convert the tensorclass into a regular TensorDict.
Makes a copy of all entries. Memmap and shared memory tensors are converted to regular tensors.
- Keyword Args:
- retain_none (bool, optional): if
True, fields set toNoneare written as
Noneentries. Defaults toNone, which drops them.
- retain_none (bool, optional): if
- Returns:
A new TensorDict object containing the same values as the tensorclass.
- Examples:
>>> from typing import Any >>> import torch >>> from tensordict import TensorClass >>> class Foo(TensorClass): ... x: torch.Tensor ... y: Any = None >>> foo = Foo(x=torch.zeros(3)) >>> sorted(foo.to_tensordict().keys()) ['x'] >>> sorted(foo.to_tensordict(retain_none=True).keys()) ['x', 'y']
- unbind(dim: int)¶
Returns a tuple of indexed tensorclass instances unbound along the indicated dimension.
Resulting tensorclass instances will share the storage of the initial tensorclass instance.
- update_(input_dict_or_td: dict[str, Tensor | TensorCollection] | T | None = None, clone: bool = False, inplace: bool = False, *, keys_to_update: Sequence[NestedKey] | None = None, non_blocking: bool = False, **kwargs)¶
Writes the entries of a dictionary, a tensordict or a tensorclass into the existing entries.
See
update_(). A tensorclass or dict source ignoreskeys_to_update: the entries that it leaves out are written too, and the call warns. Starting with TensorDict 0.17, the default will change to writing only the entries inkeys_to_update, as for a TensorDict source.
- update_at_(input_dict_or_td: dict[str, Tensor | TensorCollection] | T, idx: None | int | slice | str | Tensor | List[Any] | Tuple[Any, ...], clone: bool = False, *, keys_to_update: Sequence[NestedKey] | None = None, non_blocking: bool = False)¶
Writes the entries of a dictionary, a tensordict or a tensorclass in place at an index.
See
update_at_(). A tensorclass or dict source thatupdate()accepts, such as one with the batch size of the tensorclass, goes toupdate()instead: its entries replace those of the tensorclass whatever the index, and the call warns. Starting with TensorDict 0.17, the default will change to writing such a source in place at the index, asupdate_at_()does.
- class agilerl.components.data.ReplayDataset(buffer: ReplayBuffer, batch_size: int = 256)¶
Iterable Dataset containing the ReplayBuffer which will be updated with new experiences during training.
- Parameters:
buffer (agilerl.components.replay_buffer.ReplayBuffer()) – Experience replay buffer
batch_size (int, optional) – Number of experiences to sample at a time, defaults to 256