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

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.6.29-cp314-cp314-macosx_11_0_universal2.whl (545.2 kB view details)

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

tensordict_nightly-2026.6.29-cp313-cp313-win_amd64.whl (619.1 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.6.29-cp313-cp313-macosx_11_0_universal2.whl (547.7 kB view details)

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

tensordict_nightly-2026.6.29-cp312-cp312-win_amd64.whl (619.1 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.6.29-cp312-cp312-macosx_11_0_universal2.whl (547.6 kB view details)

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

tensordict_nightly-2026.6.29-cp311-cp311-win_amd64.whl (617.4 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.6.29-cp311-cp311-macosx_11_0_universal2.whl (546.8 kB view details)

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

tensordict_nightly-2026.6.29-cp310-cp310-win_amd64.whl (614.4 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.6.29-cp310-cp310-macosx_11_0_universal2.whl (544.9 kB view details)

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

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 aabf080cf10c1754a35c3672f77c0e405e0736c7ea9b4e2a3641ccfbfbcb162c
MD5 2016a9b857373821dcb6c2260f51a359
BLAKE2b-256 782d7fb9b820e4145d5362ef631840338753cc93bd6f01ae728e7baaafb8101b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 ad45edb9fedd819b99e5cc76b38353f9bb2ba9c325a5e9f6a86bd81c80136e28
MD5 7b94890c74ba69fa69f7e2abf3cea9d1
BLAKE2b-256 878408d7250fe2b62ba3002ac97e0bb0aac1f0454376ae23352c50dfed8e4f13

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp314-cp314-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 8b8aee10d20162a5598017d086f26f4acd7135b5988149dae18a8c36a3764657
MD5 7837562207186027ea795f17b5559758
BLAKE2b-256 a75f79042b8fb401defd0c71b394b12566aec48b9cc4f05fdd052268c0405203

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 0f673ae9dc6b81481e24be485f8b6b8e183e99f6c5d834677ee5909b1c68912e
MD5 b1843599fe2dfb3beb8b84a2686b126c
BLAKE2b-256 f432ba832fcfcdee90e65e3290082ba72cfbed606d6d9e8cdc00e3d83fb0c6a8

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 f4b3def018ba3a54ffdc882c487cd44e8ba517b7617dc2181887456c48aa8e16
MD5 e26b495096f4d6f5efb6a7b53a0a37ab
BLAKE2b-256 e8632c391c22e1d40c72ff559e4c0a0c897ba5bb83004bfd562a650f6b04e4b9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp313-cp313-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 1f04bebb106656ef8f0adfb546623c687257f77dfe1d0b75575110f44e04123d
MD5 68f9f4d3c6d43f2c326ae6263d83b8a9
BLAKE2b-256 7d4c08558e80f50aa4c6ab499acdad3611d4234425ea60847d32e68beafd27c8

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 6a575b47d13b3e2df3c06d19d45cd25612b7c163de3f163340ae144c97588cda
MD5 874336c56b5283e384a91f8db4cd32c8
BLAKE2b-256 4e3d2a09a141d6ebe15004c7fe6ee8043f4d576b0b71b0bef0bfd5785a7e8db0

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 8e61aa80582e42e5db73fcb16e78219618a450993bbadd93e66e05288e09198a
MD5 9cdf51031f46c25f0c9394467729e940
BLAKE2b-256 7b9279f15d683dc47135065aa11d2a490a9a6f21de3d0d66351f3cf5abf1b1d4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp312-cp312-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 fd216377d1d24abaa00ddda2929f842f4f1a4f770e48cb5be7c813b0ca6c9ca0
MD5 a11de466c084dc34c2b9b47c91d56169
BLAKE2b-256 5d1f2ba29f01e8f7dab60dd50aa6fac196b322ad46c4aefad38ccb845b45b696

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 64526f264f2544fdbb1207728adef0dbaa707ebaf2ec50f9e0cec0a50c30f117
MD5 72ac78bb8626497b9a53fce49b85add7
BLAKE2b-256 bbfd75075f2289bc28fa213ce2a0a683b1a5a6c12d8f2dddf2e332ef969fe1a5

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 e91a5c7f8053b1b04549469ca142824c0fae40bf8b4fbcacc32c8c3a825fe82f
MD5 135a3a0e12a7cc49cd2bc38ba12bef22
BLAKE2b-256 0b47801655e4fe61a7af7bc88c5067d0364c19bbd9f93b3e2da94b2414403602

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp311-cp311-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 8715d6580a52a86740c53ba48e2e75874a8035baf8c66a2775b157e694e7c392
MD5 ba6c5d23b33ceec217e9db84dcf68536
BLAKE2b-256 f05ccef2c50f1fa28e5225d06b070482a271a01b56056b61a04ac329ab0f1c31

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 a77f98356010ea728f85613e52809984dfcbf7d3c01f6dc56ca4141e3ebd0188
MD5 4905da0ce12d0a11bb00226e3b04f7c3
BLAKE2b-256 5b2ddabaea2c393456d351790bd48bcac7d2ac94e357ef49d87389976aa46c3e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 12e100abfa662550638e4c5a8e930d4a42b8ac6fb1b63387a8c65a3e8dbf0ece
MD5 8b05dd6fdde68b8bb90fbfd23abc61b1
BLAKE2b-256 356f8b50acd763e7c29359ef054b37b76fb053f02c440c81efb9647b30199df8

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.29-cp310-cp310-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 ba2b6c082d333f0409bf9003bf66210baf57a939532758e7044d56d66b37b9d8
MD5 fda4c2179e4d7d6871736abbda8a93ea
BLAKE2b-256 84c8222ec5b1d3358ba39976873486e385f2bddc5aeb0957d2864d2a187eea6f

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