Registry / ai-ml / tensordict

tensordict

JSON →
library0.14.0pypypi✓ verified 23d ago

TensorDict is a PyTorch-dedicated tensor container, offering a dictionary-like class that inherits properties from `torch.Tensor`. It simplifies working with collections of tensors, enabling tensor-like operations, efficient data management, and re-usable training loops across various machine learning paradigms. It's currently at version 0.12.0 and is actively developed.

pip install tensordict
INSTALL
IMPORT
SIG · TENSORDICT
T
tensordict
ai-mlpythonv0.14.0
Install
66.9s avg
Import
12515ms
Disk
4813MB
Pass rate
4/ 10
Env Coverage4 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.14.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✕ build_error
✓ 79.8s
py 3.11
✕ build_error
✓ 69.3s
py 3.12
✕ build_error
✓ 61.1s
py 3.13
✕ build_error
✓ 57.4s
py 3.9
✕ build_error
✕ timeout
4813MB installed
● package 4813MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

TensorDict
from tensordict import TensorDict
tensorclass
from tensordict import tensorclass
MemoryMappedTensor
from tensordict import MemoryMappedTensor

This quickstart demonstrates the creation of a TensorDict, moving it to a device, slicing it like a tensor, and stacking multiple TensorDicts.

import torch from tensordict import TensorDict data = TensorDict( obs=torch.randn(128, 84), action=torch.randn(128, 4), reward=torch.randn(128, 1), batch_size=[128], ) device = "cuda" if torch.cuda.is_available() else "cpu" data_gpu = data.to(device) # all tensors move together sub = data_gpu[:64] # all tensors are sliced stacked = torch.stack([data, data]) # works like a tensor print(f"Original TensorDict:\n{data}") print(f"Device of data_gpu: {data_gpu.device}") print(f"Batch size of sliced TensorDict: {sub.batch_size}") print(f"Batch size of stacked TensorDict: {stacked.batch_size}")
Debug
Known issues
breakingPython 3.9 support was dropped in TensorDict v0.11.0. Python 3.10 or newer is now required.
fix
Upgrade Python to version 3.10 or higher.
affects: >=0.11.0
breakingDeprecated methods `lock`, `unlock`, and `rename_key` (without a trailing underscore) were removed in v0.11.0. Use `lock_`, `unlock_`, and `rename_key_` instead for in-place modifications.
fix
Replace `td.lock()` with `td.lock_()`, `td.unlock()` with `td.unlock_()`, and `td.rename_key('old', 'new')` with `td.rename_key_('old', 'new')`.
affects: >=0.11.0
breakingThe `MemoryMappedTensor._tensor` property now raises a `RuntimeError` since v0.11.0. Users should interact with the `MemoryMappedTensor` instance directly as it is a tensor subclass.
fix
Access the tensor content directly, e.g., `my_memmap_tensor` instead of `my_memmap_tensor._tensor`.
affects: >=0.11.0
gotchaFrom v0.10.0, lists assigned to a TensorDict will be automatically stacked by default, potentially raising a `FutureWarning`. Explicit context managers should be used for specific behavior.
fix
Review code that assigns lists to TensorDicts and explicitly use context managers like `td.set_` if list stacking is not the desired default behavior, or if you want to suppress the warning.
affects: >=0.10.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'tensordict'
The 'tensordict' library is not installed in your current Python environment.
fix
Install the library using pip:
```python
pip install tensordict
```
TypeError: 'TensorDict' object is not iterable
A TensorDict object, like a standard Python dictionary, is not directly iterable over its values. Iterating over a TensorDict by default yields its keys.
fix
To iterate over keys, values, or key-value pairs, explicitly use the `.keys()`, `.values()`, or `.items()` methods:
```python
import tensordict
import torch

td = tensordict.TensorDict({"a": torch.tensor(1), "b": torch.tensor(2)}, batch_size=[])

# Iterate over keys
for key in td.keys():
    print(key)

# Iterate over values
for value in td.values():
    print(value)

# Iterate over items (key-value pairs)
for key, value in td.items():
    print(f"{key}: {value}")
```
RuntimeError: Cannot concatenate tensordicts with different keys: set1 - set2, set2 - set1.
When using `tensordict.stack()` or `tensordict.cat()`, all `TensorDict` objects in the input list must have the exact same set of keys.
fix
Ensure that all `TensorDict`s you intend to combine have an identical set of keys. You may need to add missing keys with placeholder values (e.g., zeros) or select a common subset of keys.
```python
import tensordict
import torch

td1 = tensordict.TensorDict({"a": torch.randn(2), "b": torch.randn(2)}, batch_size=[])
td2 = tensordict.TensorDict({"a": torch.randn(2), "c": torch.randn(2)}, batch_size=[])

# This would cause the error: tensordict.stack([td1, td2], dim=0)

# Fix: Ensure keys are identical before stacking
td1_fixed = td1.clone()
td1_fixed["c"] = torch.zeros_like(td2["c"]) # Add missing key to td1

td2_fixed = td2.clone()
td2_fixed["b"] = torch.zeros_like(td1["b"]) # Add missing key to td2

stacked_td = tensordict.stack([td1_fixed, td2_fixed], dim=0)
print(stacked_td)
```
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0!
This error occurs when attempting to perform operations (e.g., stacking, concatenating, or other tensor computations) on `TensorDict` objects or their contained tensors that reside on different PyTorch devices (e.g., some on CPU, some on GPU).
fix
Before performing such operations, explicitly move all relevant `TensorDict`s or their contained tensors to the target device using the `.to()` method.
```python
import tensordict
import torch

td_cpu = tensordict.TensorDict({"a": torch.randn(2)}, batch_size=[])

if torch.cuda.is_available():
    device = "cuda:0"
    td_cuda = tensordict.TensorDict({"a": torch.randn(2).to(device)}, batch_size=[])

    # This would cause the RuntimeError if uncommented:
    # combined_td = tensordict.stack([td_cpu, td_cuda], dim=0)

    # Fix: Move one or both TensorDicts to the same device
    td_cpu_on_cuda = td_cpu.to(device) # Move td_cpu to GPU
    combined_td = tensordict.stack([td_cpu_on_cuda, td_cuda], dim=0)
    print(combined_td)
else:
    print("CUDA not available, skipping device specific example.")
```
TypeError: unsupported operand type(s) for +: 'TensorDict' and 'float'
`TensorDict` instances cannot be directly operated with scalars or raw tensors in arithmetic operations; operations must be applied to its contents or between two compatible `TensorDict`s.
fix
Apply the operation to specific tensors within the `TensorDict` (e.g., `td["key"] + scalar`) or use `tensordict.apply()` for element-wise modification of all tensors.
Upgrade
Version history
0.14.0latest on PyPI · released Aug 14, 2026
Audit
Dependencies
torchrequiredTensorDict is built on and for PyTorch tensors, providing a specialized container for them.
Agent activity
12 hits · last 30 days
node
10
OpenAI (training)
1
Resources
tensordict — pip install tensordict · libregistry