TensorDict Nightly

2026.4.15 · active · verified Thu Apr 16

TensorDict is a PyTorch-dedicated tensor container that provides a dictionary-like class inheriting properties from `torch.Tensor`. It streamlines the organization and manipulation of collections of tensors, enabling efficient batch operations, shape transformations, and seamless device management. As a nightly build, `tensordict-nightly` offers the latest features and bug fixes, with frequent updates that may introduce breaking changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `TensorDict`, access and add elements, move it to a different device (if CUDA is available), and perform basic slicing operations.

import torch
from tensordict import TensorDict

# Create a TensorDict with a specified batch_size
td = TensorDict(
    {"observations": torch.randn(128, 84),
     "actions": torch.randn(128, 4)},
    batch_size=[128]
)

print("Original TensorDict:\n", td)
print("Batch size:", td.batch_size)

# Accessing elements
obs = td["observations"]
print("\nObservations shape:", obs.shape)

# Adding a new key
td["rewards"] = torch.randn(128, 1)
print("\nTensorDict after adding rewards:\n", td)

# Moving to device
if torch.cuda.is_available():
    td_gpu = td.to("cuda")
    print(f"\nTensorDict moved to {td_gpu.device}:\n", td_gpu)

# Slicing
sub_td = td[:64]
print("\nSliced TensorDict (first 64 elements):\n", sub_td)
print("Sliced batch size:", sub_td.batch_size)

view raw JSON →