Skip to main content

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.

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.7.31-cp314-cp314-win_amd64.whl (648.3 kB view details)

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.7.31-cp314-cp314-macosx_11_0_universal2.whl (574.8 kB view details)

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

tensordict_nightly-2026.7.31-cp313-cp313-win_amd64.whl (646.3 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.7.31-cp313-cp313-macosx_11_0_universal2.whl (574.6 kB view details)

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

tensordict_nightly-2026.7.31-cp312-cp312-win_amd64.whl (646.2 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.7.31-cp312-cp312-macosx_11_0_universal2.whl (574.6 kB view details)

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

tensordict_nightly-2026.7.31-cp311-cp311-win_amd64.whl (644.6 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.7.31-cp311-cp311-macosx_11_0_universal2.whl (573.8 kB view details)

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

tensordict_nightly-2026.7.31-cp310-cp310-win_amd64.whl (641.6 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.7.31-cp310-cp310-macosx_11_0_universal2.whl (571.9 kB view details)

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

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 e8de8de55035c16d2b5bd7e9c7368decee75d4bb2c088c7d4b7e4a97bb801791
MD5 d169d9b495319c0e547b60a424524f7b
BLAKE2b-256 5cfec22b82ff5111acf646a77d9da8997c8c8292279e3f2cbc9ed2cc6aad6cc9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 e5aa76a362ae841e9f0ec575dc28a374f48f72c2fa7ed40144c02708bde86425
MD5 12dfbe92cdffcaa49cb9bca215c19d81
BLAKE2b-256 19071117d8e1073e246d24f3262760e26fb6bac8ccb61c6582f70943ee12e744

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp314-cp314-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 6b9543fa3ab3a43435993a88f555a561acbb3c690ee2267dcb3c9f9003236ee6
MD5 b225359d0d5674eb9b49675866215a20
BLAKE2b-256 b78f7296f2cb41ce005bfb5ebe84fe08027b682e38a29316dc96c03edc02c311

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 eceba1e9e2f5bf2103d3ca31e335216d46714b671233fb33ccd95544b35b2881
MD5 9194e5ab254965fec4d7ec98470c79f0
BLAKE2b-256 eb680b5ff3636ebdf2acbe794e0b93c999d64b6285063178dced858d2dcba383

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 1d31014b250b3c42c75270de6d3b80b89b969fc8c149811d19af66e526744134
MD5 529c722bf369e8a87eefa02bfcd992c6
BLAKE2b-256 c6e339160cb4f1f194f2aa3b42767ee52c3c98a357ab96fab5bdcc8a2a6d60f7

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp313-cp313-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 87b71693b087557e1a757f77b90da683918fab88005677d79908cc1d1eb40744
MD5 5ecf7d8af0ffc468520addd4fa045f8c
BLAKE2b-256 de402a1de57dd1e0d318a287293705b057f693b02fea87f9a509651e32cdaa8b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 3ddfd3e04c364e3585664ded9b41810f4fa901fbee27b0ff7b3946a2bf361554
MD5 1e7a56f972878aa446e56e740c832403
BLAKE2b-256 7f56833aaa5fc2e7081eb007ff77e6a44e51ee7434be9b108822589242695fe6

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 aadef960f8aa4a078e50b6017ad73f4a771eab0b9364c7d7b0ed816f954a4142
MD5 65c676af8c006d77069be8815f137694
BLAKE2b-256 39e5ac21c2b0ab5360459445be3baac60cb375f0027bd26b534fa5cd3a9d1ebe

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp312-cp312-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 198b1452b2f9f05ed8a77c2ffc09bbaab9a35c6c11db6d7e525e439868791529
MD5 ce268238389fe36da2e029c2544df608
BLAKE2b-256 2defc2c49c6be6a39439ead3bed6cea5c6c3c0f1599d0b9efec85bc32f468bbf

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 bc1845980a2807a37715899b863f46e2dfa0310e20a0f274b5db4af861467ed6
MD5 e7bc1bbd74c6c8265663ab9bc8ad24d7
BLAKE2b-256 9c5b107c24782362320f726ab2fd4f3f1e372d4f72282861172884ee91632c3e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 6219969313dd279214801aef774e9fbf218775962230d9d2291a92f436fa3652
MD5 8614e1a07ea87a3af6125c82b603e5b4
BLAKE2b-256 5d2e8ed2be6e5d58c8ca28ce57be9b990d529bb54e964cea0d8c8b4176408340

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp311-cp311-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 0e01777cc3e1b5dc02fe2fe89bde438e90f1f96cab1e28fdeddb2192070f7816
MD5 25ce06c3e28c259ac8071aab0972238b
BLAKE2b-256 0ee69be984a9668d768e94426acfd6e8bfc981035d1eeed4ac24a709c19b06ac

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 0ef5e85777e2ac93193277d11b2b4afa22bab5d54d7a584ce679bd0ad9b89bca
MD5 c469b935277a05a0764f561deb35f5b8
BLAKE2b-256 cd9a98a306894bc8b84c451c26ba39abc031cfb84d2550a5a9f9071bc7b55b34

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 1582485ee2a5645acaab8e0a20d585fe9ebbd7436b60d2a0d63a63efed80162e
MD5 681b97e2289037fdac5764c4665df90d
BLAKE2b-256 2a4b6c416461241ed75e7b5c3834b8fea84644ad779eb4fcd913d25f8ded890d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.31-cp310-cp310-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 429bced70697b71586c2c177a03a18e1a8047fd683542ae779010b83613da6bb
MD5 91b3bbcae873b6c1e8a47f9d993591f0
BLAKE2b-256 19860f618529bd641aaa7f5ca9e42bafa4ad562ab6add8f3959d6c3cfe6d64fa

See more details on using hashes here.

Release history Release notifications | RSS feed

Supported by

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