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

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.6.16-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.16-cp313-cp313-win_amd64.whl (618.9 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.6.16-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.16-cp312-cp312-win_amd64.whl (618.8 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.6.16-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.16-cp311-cp311-win_amd64.whl (617.1 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.6.16-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.16-cp310-cp310-win_amd64.whl (614.1 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.6.16-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.16-cp314-cp314-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 9001e8b8897d83281f017d54685ab9fe16e60769b939d56449f2599051f39978
MD5 29042aba5b63caa26be94cc3bf09623d
BLAKE2b-256 b793ad49aa02582d1048e2f5805f076a23f059a539160bc4293c4805ecda3bdc

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 9e0db60340e1691bb13d8c87789325d75f9e601e0f27d309efc4d3c909a72a98
MD5 aa8d5ecdc5b36a63ea1bb74acfc9c510
BLAKE2b-256 cdd2c8fefa2a69406eaed09560cb999be007ffc51610b748c2fc5d58adb1f02a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp314-cp314-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 a6d81438afc6f61800fdccdbc1fb2576453b8132b3bc8f77a471c33c2e5f617c
MD5 eb511d77b2a964bdd1e90ad3d2e89433
BLAKE2b-256 acb72ccc64d3b0a07898b364bc9743a5a27b67dbfdfca592bfbc130884064c96

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 f182e5638fad8ec65a015e84f676af5edd1e05692b173d90bb4f575082be12d3
MD5 44f0b0d6fbd9282851055005bea23968
BLAKE2b-256 5faea7ef1743647e5be6edeca1bb18eba403f5b77b3d16400f833470a30945e7

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 c5af8eb6e57e103c4364a3609429022109b354ef6fe1efe69565b9a76363e2d4
MD5 51de8fbb2ca118d9c28aaad2e19be8f1
BLAKE2b-256 f06aeaf25d42d7689ad22658decceaca96e2a790fed73bea8413a9460df698b2

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp313-cp313-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 f43f2490a35bbaa2f040375d203cbdcd3f2d7414c1e63061955fc688d9c60785
MD5 1cacda3613eeb062bca305879bc785dd
BLAKE2b-256 7b0465f160873d766462ecf0045ebd8fe204595a1b54622c00ebe94bea9149d9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 4f9f1b6e09381e82ad67851bd83d3b859d66b22b4af38ac8ecff8345b18d517b
MD5 7dd6aa4668d694f19993940acf295b2a
BLAKE2b-256 457dab607dee865054475eb3cdc039f7562173a6d791f7fefcdea8f372def60c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 022631e7380b1b6882999f67da7e31fab6deb9abcdde42be395c777025175011
MD5 fa3f719974499c79e6752cac8cb21450
BLAKE2b-256 26c844c7c2bd14f357f0d5e7a8fa087a4b17d9f9eb7a1d7ee70c49253c852c9d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp312-cp312-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 186b94a8c13368633cd59c2d007db228bea671b57ee002789b929a379f53d93a
MD5 913712dc8b7fef9a4ad97461d063e822
BLAKE2b-256 906c8e580238148ed30e274ec9649d8fa30ac39526336a6b459b9dd675b4fe9b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 5e33cc0cc5689ce04ec9e20b117f486a2ff9549bcbe4cb8cea71504fa4f996ba
MD5 bfa69f083f78c29155754a3254419412
BLAKE2b-256 114ca20a0afebcea8235d429f396d2c702afc068003fb8165ee185bc0ea7ebff

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 7b8240bdc09604aa20fa4293a99d6b7f86b2836f534b903275fd58dce8c523e7
MD5 0cd6feb55780a6dc4fc26b66d1a1f665
BLAKE2b-256 29601e08da5e038cdb85cf73fd4b9957a52558e610e3481ea807fd3e96931b42

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp311-cp311-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 ce5334160964e49b78643925f391e3a8f192be40e97f688d2673421ad732148b
MD5 5e440f9580c395d3e5d7c3849833a84b
BLAKE2b-256 e67aeb0aafa6f19a820346b0be84c2618df4a66a0ebf8fc65c879b85c8ff0862

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 10711f4ed47ca1959504b7550623f0cacc385c127093282a7a0e8ea5cc88c4b1
MD5 d3930fec0e8259877f7f6637ea6207eb
BLAKE2b-256 80d53e3dc977b529487b755236676a19bfb4bc4ae6d602ce573dc67fdad3166b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 5db03c1f4e831d63b60349534fd0f29fed187b669b2c57104be5fb3f1ba7bf08
MD5 713638a913541f32ac0693f6a013bacf
BLAKE2b-256 5ed5aebdf4f7699ab082af59773b56efe4cc0df0da0ec9371bf579e6b6ade6d6

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.16-cp310-cp310-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 ca8d9520a29df1bbb4b34deae7ea2a51f668aef0514414f8cb93d37b1336478f
MD5 ece43a2abe7bc41c92ca24e12e966ee3
BLAKE2b-256 b15b5db074e4bda2df7e2a3fc946da069f13f81730d106c01246629b89dfb8fd

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