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

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.6.27-cp314-cp314-macosx_11_0_universal2.whl (547.5 kB view details)

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

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

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.6.27-cp313-cp313-macosx_11_0_universal2.whl (547.4 kB view details)

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

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

Uploaded CPython 3.12Windows x86-64

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

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.6.27-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.27-cp310-cp310-win_amd64.whl (614.2 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.6.27-cp310-cp310-macosx_11_0_universal2.whl (544.6 kB view details)

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

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 d568d447c09dfe85a3e4be9ada1eeff2968ca16eb5576bce6cd93ebdecf66cd5
MD5 58e2572efe619cc8ef2298f61581aed4
BLAKE2b-256 060f6e900b35f88132a10fe68a081d4e49b0997c3fde65fa6fe23d7c8cc444e9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 3c5ea121ab8d1f8da05f4f5543e77e0179cd06378d71032d647d0009fde21b30
MD5 bbe38a3c22652c433ad2c19717a25e56
BLAKE2b-256 0d82fe5da28859277e80bfb1e594f0ef5bd8639463643d8b62d86ae333c38e54

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp314-cp314-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 476de65a4c175983e0182721423e9a81ae57cf78e01db67d73b0caf00f016e1d
MD5 438f0f477eea65e9e626243880f25f74
BLAKE2b-256 a39f8e42ca7acc72d4c88a929b3e5feb77b6ce173e896b07e31ecc6d35b43096

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 78164469123465843a861841f40dc3f650af3c50790e838b32863ebcf9f66d39
MD5 23f71a6b39f3719e3fe7395b84a8cbb6
BLAKE2b-256 04c63a1bc5b84ab4d16712eb0253a3c30dd23357b6258eb7aa5c4a255d635cfc

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 c18257c37b4041995bc7a64576350748ff2f128cb418b59b97d48d3edb02241c
MD5 b2a3dcc39c62d13211ea54d2a13468a9
BLAKE2b-256 27c2adf7908f7835124b13b08c31edb7d43b53049823ae86e611cc3d27a5f8a5

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp313-cp313-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 1f60a4c091041b0820ca21c53c20b1bd0f00d50792d4046ff038c32da5f410cd
MD5 6eae35313ce112a7ed68520167dcb3a0
BLAKE2b-256 6c71a5ae71cb596020175fcc96873e1313be7cf843e680817b9252b15415beea

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 3ebaa7d8e94624988237e854838182130c55bd73c42afa60c2bdfdb3a5c92075
MD5 d136869ad608c24c8689085f2a49a28c
BLAKE2b-256 0d4abb57be0eb0dd3efda2690aac02f1687c7291c43addaa1fb98c22617501e9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 832da1787028feb2e55a1fcbb17c68bc864854192e08e54122fb08d15d7bb2b4
MD5 f970ae751c1c218440db6ba2e043e836
BLAKE2b-256 f7cd0e173b14808f5dbeaa5918297562d661c67643ccdac842cc79f76e31ba92

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp312-cp312-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 0484f8b82a7030e185bf4952737e563a127501693da30f5f045924beca1a6a57
MD5 b7255df7b72146b86925fcc2f6c2f0f6
BLAKE2b-256 955a22b6f3ccb750f31e122463e2c84b03b98637f0ead192ea34001fde9bd4fb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 f5c426771f7608bb17bb2399363006c5f89d8a301b100f5f407c3dc116c20d6e
MD5 d84960e16e7f1e5173fde74553cd2935
BLAKE2b-256 ddfa6ef7bd460a4d5be4f13f22e9767c9abd32e4a97870d3edaef809b597542a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 85dc03194c70205f9acdcff26be42572b58c6d18ebb906a8d00c864829e748e8
MD5 c8d359038239ccb3ccfa931d8d06475b
BLAKE2b-256 79a0886cd5d798b02ce20bf42c1075671b5fca562511ffd17e3c96603afcad38

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp311-cp311-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 a4bc713d765b2396ba888557ef5b9a0532b326809a72a464555965c70069275e
MD5 3288c85dc5c736911b5f20b2bff29513
BLAKE2b-256 b4220ceb25c841f3f0c6683629a2004e1cc2cbe908addf3790b3450f467430ad

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 25619a8609eeb25a9dd0360ec89267d83fb593eb8bef4442f75cb3313f4454fb
MD5 6c1543d04a8c0bfca7136ce76e13fc58
BLAKE2b-256 de416e4fa442e710d0ce9d1c7caf0f3c7dd43a43943ccbc001643dd386748dfd

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 39c327d497a257c0126e13d6f625b01695fe6938edc8bee78c696e764caf978d
MD5 ef72b3c36a7c980f8e115a995acf1e8f
BLAKE2b-256 fea540b8f4453286183c7c493ca04f7bc3742ff242c1713f19fc765ce40e5a40

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.27-cp310-cp310-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 79b5f2a9c48e824bc38f13236cfbbc175abd0b3b93c6c00af6513168ec0bcfa2
MD5 357b628e8c0cb30499b8bde3d127fd28
BLAKE2b-256 db7f37ca9b2f663ab267d1c6052726de21bd89e55c94c8e3cea31cd9ffbc796b

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