Skip to main content

TensorDict is a pytorch dedicated tensor container.

Project description

Docs Discord Python version GitHub license pypi version Downloads Conda (channel only)

TensorDict

TensorDict is a batched, nested dict[str, Tensor] that behaves like a tensor.

Move it, slice it, reshape it, stack it, save it, compile it, or do arithmetic on it: every tensor leaf follows the same operation, and one shared batch_size keeps the structure honest.

TensorDict(batch_size=[32])
|-- obs:      Tensor[32, 128]
|-- action:   Tensor[32]
|-- reward:   Tensor[32]
`-- next:
    `-- obs:  Tensor[32, 128]

30-second demo | Why TensorDict | What is new in 0.13 | Patterns | Installation | Ecosystem | Citation

30-second demo

import torch
from tensordict import TensorDict

batch = TensorDict(
    {
        "obs": torch.randn(32, 128),
        "action": torch.randint(0, 4, (32,)),
        "reward": torch.randn(32),
        "next": {"obs": torch.randn(32, 128)},
    },
    batch_size=[32],
)

mini = batch[:8]                 # slices every leaf
device = "cuda" if torch.cuda.is_available() else "cpu"
on_device = batch.to(device)       # moves every leaf; non-blocking internally
scaled = batch * 0.5             # arithmetic on the whole structure
merged = batch + batch           # leaf-wise TensorDict arithmetic
stacked = torch.stack([batch, batch], 0)

print(mini.shape)                # torch.Size([8])
print(stacked.shape)             # torch.Size([2, 32])

The object remains a mapping, but the batch acts like a tensor. That is the point: write the operation once, apply it to every tensor that belongs to the same example, rollout, batch, parameter set, or dataset shard.

Why TensorDict

Plain dictionaries are flexible. TensorDict keeps that flexibility and adds the parts tensor programs need once the code gets serious.

With a plain dict With TensorDict
Manually keep leading dimensions aligned One batch_size validates the structure
Repeat .to(device) for every tensor td.to(device) moves the full batch
Hand-roll slicing, stacking, reshaping td[:32], torch.stack, td.reshape
Manually recurse through nested state Nested keys are first-class
Duplicate arithmetic over leaves td + td, td * scalar, td.abs()
Invent checkpoint formats td.save, td.memmap, load_memmap
Hope generic code keeps working PyTorch-native APIs, torch.compile coverage

Use TensorDict when the unit of data is not one tensor anymore, but it should still move through your program like one tensor.

Performance is part of the API

TensorDict is not just syntax for recursive Python loops. Core paths are built for high-throughput PyTorch workloads:

  • Arithmetic dispatch: operations such as td + td, td * 0.5, td.abs() and in-place variants apply directly to leaves and use PyTorch foreach kernels where available.
  • Device and host transfers: D2H and H2D copies are dispatched across the full structure. TensorDict uses non-blocking leaf transfers internally when possible, so the common path is just td.to(device); pass non_blocking=False only when you need an explicitly synchronous transfer.
  • Shape operations without boilerplate: indexing, view, reshape, permute, unsqueeze, squeeze, flatten, unflatten, stack and cat operate on the batch structure rather than on hand-maintained lists of leaves.
  • Low-allocation workflows: lazy stacks, preallocation, memory mapping and inplace=True shape-changing operations help reduce peak memory in data-heavy pipelines.
  • Compile-aware internals: TensorDict is used in compiled training and RL loops, and the codebase carries dedicated torch.compile coverage for hot paths.

For deeper numbers, see the benchmark notes.

What is new in 0.13

TensorDict 0.13 focuses on making structured tensor programs more practical in large training systems:

  • Tabular import/export for pandas, CSV, Parquet and JSON workflows.
  • More inplace=True shape operations, including gather, repeat, repeat_interleave, roll, reshape, flatten, unflatten and contiguous.
  • Improved torch.compile behavior for TensorClass initialization, dynamic-shape export, locking paths and shallow clones.
  • Safer memmap filenames by default through robust key encoding.
  • A migration path for module state preservation with to_module(..., preserve_module_state=...).
  • CPU-only release wheels for TensorDict, avoiding duplicate GPU wheel artifacts for a package whose compiled extension is device-independent.

Patterns

One batch through the whole training step

TensorDict lets datasets, models and losses agree on one container instead of a long argument list.

for batch in dataloader:
    batch = batch.to(device)
    batch = model(batch)
    loss = loss_module(batch)

    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

That loop can stay stable while the schema changes from classification to segmentation, RL rollouts, model-based prediction or LLM post-training batches.

Nested data without custom plumbing

td = TensorDict(
    {
        "agents": {
            "policy": torch.randn(64, 8),
            "value": torch.randn(64, 1),
        },
        "env": {
            "reward": torch.randn(64),
            "done": torch.zeros(64, dtype=torch.bool),
        },
    },
    batch_size=[64],
)

policy = td["agents", "policy"]
td["env", "reward"] = td["env", "reward"].clip(-1, 1)

Nested keys are part of the API, not an afterthought.

Functional modules and parameter sets

TensorDict can hold module parameters, swap them into modules, vectorize over ensembles and make model state explicit.

from tensordict import TensorDict

params = TensorDict.from_module(module)

with params.to_module(module, preserve_module_state=True):
    out = module(inputs)

This is the same foundation used by TorchRL modules and functional training utilities.

Checkpoint and share large tensor batches

td = TensorDict({"tokens": tokens, "scores": scores}, batch_size=[n])
td.memmap("/tmp/batch")          # memory-map every leaf
reloaded = TensorDict.load_memmap("/tmp/batch")

Memory-mapped TensorDicts are useful for large offline datasets, replay buffers, inter-process handoff and checkpointed intermediate state.

Key features

  • Tensor-like collection ops: indexing, slicing, device casting, dtype casting, reshaping, stacking and concatenation. [tutorial]
  • Nested structures with tuple keys and predictable batch semantics. [tutorial]
  • Fast memory workflows: asynchronous transfers, memmap, consolidated tensors, lazy stacks and preallocation. [tutorial]
  • Functional programming with parameter TensorDicts, to_module and compatibility with torch.vmap. [tutorial]
  • @tensorclass: a tensor-aware dataclass for structured tensor objects. [tutorial]
  • Distributed and multiprocessed pipelines across workers, devices and machines. [doc]
  • Serialization and memory mapping for efficient checkpointing and dataset storage. [doc]

For a longer tour, start with GETTING_STARTED.md or the online documentation.

Installation

With pip:

pip install tensordict

With conda:

conda install -c conda-forge tensordict

Nightly builds:

pip install tensordict-nightly

From source with an existing PyTorch install:

pip install -e . --no-deps

If you use uv with PyTorch nightlies, keep torch pinned to the PyTorch wheel index or install TensorDict with --no-deps so the resolver does not replace your existing PyTorch build:

uv pip install -e . --no-deps
uv pip install -e . --prerelease=allow -f "https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html"

Ecosystem

TensorDict started in reinforcement learning, where batches quickly become nested trajectories. It is now used anywhere tensor batches are structured data: RL rollouts, LLM post-training samples, robotics trajectories, simulation state, model parameters, checkpointed datasets and scientific pipelines.

Domain Projects
Reinforcement Learning TorchRL (PyTorch), DreamerV3-torch, Dreamer4, SkyRL
LLM Post-Training verl, ROLL (Alibaba), LMFlow, LoongFlow (Baidu)
Robotics and Simulation MuJoCo Playground (Google DeepMind), ProtoMotions (NVIDIA), holosoma (Amazon)
Physics and Scientific ML PhysicsNeMo (NVIDIA)
Genomics Medaka (Oxford Nanopore)

Citation

If you use TensorDict, please cite the TorchRL paper:

@misc{bou2023torchrl,
      title={TorchRL: A data-driven decision-making library for PyTorch},
      author={Albert Bou and Matteo Bettini and Sebastian Dittert and Vikash Kumar and Shagun Sodhani and Xiaomeng Yang and Gianni De Fabritiis and Vincent Moens},
      year={2023},
      eprint={2306.00577},
      archivePrefix={arXiv},
      primaryClass={cs.LG}
}

License

TensorDict is licensed under the MIT License. See LICENSE for details.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

tensordict_nightly-2026.6.20-cp314-cp314-win_amd64.whl (620.8 kB view details)

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.6.20-cp314-cp314-macosx_11_0_universal2.whl (544.9 kB view details)

Uploaded CPython 3.14macOS 11.0+ universal2 (ARM64, x86-64)

tensordict_nightly-2026.6.20-cp313-cp313-win_amd64.whl (618.9 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.6.20-cp313-cp313-macosx_11_0_universal2.whl (544.7 kB view details)

Uploaded CPython 3.13macOS 11.0+ universal2 (ARM64, x86-64)

tensordict_nightly-2026.6.20-cp312-cp312-win_amd64.whl (618.8 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.6.20-cp312-cp312-macosx_11_0_universal2.whl (544.7 kB view details)

Uploaded CPython 3.12macOS 11.0+ universal2 (ARM64, x86-64)

tensordict_nightly-2026.6.20-cp311-cp311-win_amd64.whl (617.1 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.6.20-cp311-cp311-macosx_11_0_universal2.whl (543.8 kB view details)

Uploaded CPython 3.11macOS 11.0+ universal2 (ARM64, x86-64)

tensordict_nightly-2026.6.20-cp310-cp310-win_amd64.whl (614.1 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.6.20-cp310-cp310-macosx_11_0_universal2.whl (542.5 kB view details)

Uploaded CPython 3.10macOS 11.0+ universal2 (ARM64, x86-64)

File details

Details for the file tensordict_nightly-2026.6.20-cp314-cp314-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 e3c30f89d009935baec861fb0cd1a28bfcd055fe98c4354cf4bd52e92b7b9ab1
MD5 b1f5fc8c2c8915ea72e43ac274953008
BLAKE2b-256 35dded2e03e2099bb76402164bd511ba7ded81910e5be13869ae5b6a87323ff2

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp314-cp314-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 f65ef9b366c183b147f60140715c9ad843655d11ad6d7a7fc0a500b1da1c2df2
MD5 b4068de0bd387fc1d1de97ebd227dd3d
BLAKE2b-256 eda7f7b6876dd938907022a79f6b0431feadef6952cec428ccabc59de6a96681

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp314-cp314-macosx_11_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp314-cp314-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 f3d375fe83b0adc32a3f1fe50cf3a6e773c389553317566d2f592366db499588
MD5 f6ed31057813ca70fe34bf6316ea055e
BLAKE2b-256 2d5e3250e598b92ca69c055751d7ef8466e14d6e09086a07e889669cbd107815

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp313-cp313-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 abc05afe1651bf538bab6d4dc591b6ade084c68e960b5bec945fe6b0287d4f57
MD5 1b4c7c361403ad5e96d3d024014a7f9d
BLAKE2b-256 065a290365108083e11ff51245c72a7a7018526efc883cbb92a9640723ada646

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp313-cp313-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 1676fc4ec77b4f0324dc83264e88d01213e0976aea774cfa9b465455f5851c0c
MD5 4367894829bf0e53a449576149608e39
BLAKE2b-256 e2d3f867ee5c2575a0f3f554204930006ea9c727a433c306610a025cdb4ba002

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp313-cp313-macosx_11_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp313-cp313-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 5e7501d4cfeed136e581052c7dfab6bfac3f9420968859a57c58c15e1c6cc72a
MD5 36cd72c26d554d06cec8686bae3be956
BLAKE2b-256 733e67c4e9d989d0a6e912becaef88ca9d1d959bb8d162ef00538a41a4de358e

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp312-cp312-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 e7c232385b16883f4132cfa0296ad0e861b9d627fe377f1a81373c7ba374e575
MD5 06b4c2fcfcde9457e9c87c13a01412bb
BLAKE2b-256 2dd0941f4cbceffdb73d15ea4df502a711c7735650fe7cedd64dcdce5f892edf

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp312-cp312-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 5ad681c84bb63a1f0f2c99f92b2de8158bc5e24933523ab52a9a5ab1012c7039
MD5 54cb448bf7059dcf4f85985cb87cacfa
BLAKE2b-256 eaca13c973cde85abc83718b6bde4c468c52c8cbdb165bc9d6d26e2c71d83724

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp312-cp312-macosx_11_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp312-cp312-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 4ee7b7b18fc1454a01e25cdea99bcd3dd85ee4aa3dacd95e6444374e36206961
MD5 247e8f17717c9cb27bae3d30c28df6a9
BLAKE2b-256 dffe531b64cb4007bf66dafb38acc71892cbaca390e91a3a906c41106b073c18

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 a620cda1e9e313cd280ba48f4d77fc7cec2f657bf658a17cce254352ae10df85
MD5 edc2dbec7274fd84ffd5c4ff1b28d849
BLAKE2b-256 c473c5cf54f9692dd44179bc63dca41b3bdbc247be02ca46e7bed8ead90f9817

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp311-cp311-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 e89c81e409d06dfa8224b80fec274bacb35e2a4d45bfcb52d0a38fbe63deca73
MD5 d80a08e25ffd59c5c4f68283f3c48602
BLAKE2b-256 f6f39f7116150e3079c1c876abdcf6df9da6c5419f26f94b688dd4f033b98f08

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp311-cp311-macosx_11_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp311-cp311-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 b5f89af38d3893d0084f782e712d828e1797c85632c010241fb7cb605efa07ef
MD5 eaf32b190c08b068ee7f9dd92147d99d
BLAKE2b-256 d2438de97a40fb3f929f7a09ccb2061450ae134bb842caa5611a57aec69a895a

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp310-cp310-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 b56d18c3b1c51e7eeeb535108838844fedbb7f1d8ca46971c75ff4f4b0ce8c8c
MD5 48f2b60d04d228b6811c34285aae7769
BLAKE2b-256 27f08eed3c35dd4df8f06fb182ac21543154074f1b9ee5c2b75de94935651adc

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp310-cp310-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 0754a5fb954c2ced8bfda4f907bf21ea500dfc283dde6b0c55e9ea555617e529
MD5 1710e30c53a96431ee1e668b333e2f3c
BLAKE2b-256 0ba270c833024844a983cb991fd4783e165dd51871ae6d6063a18750d016c20c

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.20-cp310-cp310-macosx_11_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.20-cp310-cp310-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 8647da20768a76f6d374aa2d6eef360fdbb641307d30ca35bf50905c01bd1e45
MD5 5e20ac6f22accbb67899e8aeac804231
BLAKE2b-256 0a0a24715d257454fc7df7e24f05c53f2c298bc9a2e26e4d3a56eb7dbdd50a3c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page