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

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.7.7-cp314-cp314-macosx_11_0_universal2.whl (553.6 kB view details)

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

tensordict_nightly-2026.7.7-cp313-cp313-win_amd64.whl (625.1 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.7.7-cp313-cp313-macosx_11_0_universal2.whl (553.5 kB view details)

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

tensordict_nightly-2026.7.7-cp312-cp312-win_amd64.whl (625.0 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.7.7-cp312-cp312-macosx_11_0_universal2.whl (553.5 kB view details)

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

tensordict_nightly-2026.7.7-cp311-cp311-win_amd64.whl (623.4 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.7.7-cp311-cp311-macosx_11_0_universal2.whl (550.0 kB view details)

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

tensordict_nightly-2026.7.7-cp310-cp310-win_amd64.whl (620.4 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.7.7-cp310-cp310-macosx_11_0_universal2.whl (550.8 kB view details)

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

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 b5f7e0350ff4540e71296512a9f3fa10a40e63bd2710c466b7f7000a68707d27
MD5 9e1cbe42723c35d7b5e1aa26f9d07ed4
BLAKE2b-256 f1215cf21e391e8d678f75f1c6ac35407dcc8df098937e7d8e6c14c6dfacfde4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 59a5cfa0805b9b0669b28a68272dc2a33a26b675e7e60296ae2d96780fe5192f
MD5 89f1c78a978c012cb13241edf47eab5f
BLAKE2b-256 1a81568db2679ac895f9a296c6b6b181172a243668235d0f37ad98178e47614d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp314-cp314-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 a179bdbcc06c5c6b1b0d98e8a8b6acebbcd1bb49e333d321c295a0b00489d414
MD5 bd81bbe8b67ce6c17ac0c129750c6bcc
BLAKE2b-256 22e265b4b12f0d5b8d828cfa446e9bf42cc8c53d1c344f5b77aefc004aca5aef

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 9559cd98a5e1de10af92765f1ed73891f7a96214f16c3b46d5e06de1450d253e
MD5 8cee09c3f120a99d1b3668f74be94c6b
BLAKE2b-256 6a98938be34fb788a0b8e32f55ef35ae67b8f6a6143069a84e7621ff73c6f87f

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 8b77773b3e2bf7cd8d9278e40ef751e23b748979c3ea14a8709ebe5a0ac6f282
MD5 1a602cc3ab51a8aa38016c11b62018a9
BLAKE2b-256 8f5a04771ac6a7c0d9a1f28244fea4def0b592229ff63c7871e8b1799b51b101

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp313-cp313-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 4283344023529d9c180c37b8c336fde10eea09ebe9d0c40ea4813dcfa7728d9a
MD5 026c67a91438ed397f3776d036094ceb
BLAKE2b-256 096609b9515cbceb30109b602d3a52ca3b0db0a2a0c0420eaec997cc8be9cd8f

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 aa6cf6fda53a9321bb988e2a9b607746fd40a9a9361c91d202f318d05bfac1e0
MD5 ecb40f884dd0671fa06e48b39532fa6c
BLAKE2b-256 305fb2a3b32373fe1bcaa80380740638459f5232695a7f220e593ac8412fd400

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 8a59b2d8febfbbb19cf48b387bec67dbe1977bbf30185a85a998f990b2892864
MD5 6101b1a91ca7866627882ff2533ffd57
BLAKE2b-256 fdbead997f9322df65eb3c6edd82a8ee237dc14be8f9278e6eebe50ec84b5cf6

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp312-cp312-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 9b8281f13689025bc713060717f26aa0ce9ad5916430d9290bc20469bf1469b9
MD5 0d08f799c25eed2aa2a2b96890a55dc4
BLAKE2b-256 d237413a4733cab0fa284d28c14994d1be8f90d26146197b69f5788c05640281

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 370c4eaf0f938db775b225a06eb3f94eeb0040f62e50523561e2f5a8d1a32daa
MD5 fb97d9918f75f58960628375ece0c26d
BLAKE2b-256 2b0dc860e3b23b5f3ea57b07fad1fe0dac6e92664e103aab5a1b19485fd489cb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 41ec22a89c9767f654f2b82e8295b54ec1eed73310b45a9167e3c554c3186675
MD5 49a4761df16944d4d215986cae24181f
BLAKE2b-256 d62ed0eb1d09405c055bf22b0867ab1c724746d84b2f295c352b13d7dde66446

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp311-cp311-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 c70fa4cb56a143d09317270f6eb1145f291d9961af088fc8b2ae0c087b13919e
MD5 700af6b89f30f2ecce79f1a20c9771e3
BLAKE2b-256 42df07c78ab050493734f66ea629228d40de0f041768e14a1e3edaf03a3d8d80

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 a2b9cdad78de0d26a222e93163460b2755faac629064c1a671794b1318da71dd
MD5 c04b0b7394bfc6c3019ed6a7c09af693
BLAKE2b-256 ff65268919d8bb14a55f170c2ec7be85227c8b19a1df81f1888326fb009401a3

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 4740753b56e58791e590fea22aeb6a9e243bb64de6791fdb998ce07916334eda
MD5 db185c9258cba7144555bc44143ef216
BLAKE2b-256 7ec2b2c888e4490ab9647f6b49ff4060053619fa5d78f28045c617b962d4ec64

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.7-cp310-cp310-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 e8a264609af6e58dcb13b8891357bc679c62e223a88a4ffc46bb5f1878edfaab
MD5 fd1b43ad9ddbfc2311bbd6820687b8a7
BLAKE2b-256 20f26e2f54822c54ac4bcfa4f66acfcdb71beb6f67f6d3d48390e5305d7587d0

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