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

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.6.5-cp314-cp314-macosx_15_0_universal2.whl (542.5 kB view details)

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

tensordict_nightly-2026.6.5-cp313-cp313-win_amd64.whl (613.2 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.6.5-cp313-cp313-macosx_15_0_universal2.whl (542.4 kB view details)

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

tensordict_nightly-2026.6.5-cp312-cp312-win_amd64.whl (613.1 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.6.5-cp312-cp312-macosx_15_0_universal2.whl (542.3 kB view details)

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

tensordict_nightly-2026.6.5-cp311-cp311-win_amd64.whl (611.9 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.6.5-cp311-cp311-macosx_15_0_universal2.whl (541.5 kB view details)

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

tensordict_nightly-2026.6.5-cp310-cp310-win_amd64.whl (609.9 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.6.5-cp310-cp310-macosx_15_0_universal2.whl (540.1 kB view details)

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

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 b806d87143ea0c6b2ba38efed8466e9d58eadd383083a9ab096fa211f55d685a
MD5 72807f5195f0a67d1386b8acf22eefb1
BLAKE2b-256 c268e3bc89f0cfda8b155b79f5fb10d8614b10d9726fb26e99b5b4426357d312

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 14cd2f70fd43b59d756540b49376a71fa0e9e2b05c2b0dba2dab0afaaa5b00df
MD5 0ab3fcfeb7ef42c5961f857170d7b450
BLAKE2b-256 d52bc92417d623c77bd3e1ec2866c2c08722b1dd22a05e0f13fa4ec09efb879d

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.5-cp314-cp314-macosx_15_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp314-cp314-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 3ca1781a3844a9e40b153e28ed3d66a7735231036e79b47036720ed246bbc7ef
MD5 43c5e4553eab2521054dbc29e9dec660
BLAKE2b-256 cf06d056e3ae7d482d4b8bc516ab3e3476b077d50638dd96ba963e779a3c3fc4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 fc3f4c7eec4e9b0f6ebd52110ed3ba218cac6a02ffc4cd0eccb530cf2f1d74a2
MD5 15d4f298724e69abec57955f18e20654
BLAKE2b-256 2511034426c8b4722d6c5950af697b93fd2a436fc7e7b2644de31ff869dd2a95

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 fe80e45cbd364f3f6111117a3de94c0377f76b53e588295e61733bebcbdf3bdd
MD5 dbdea65316cdd3c64627597ff4bc87e5
BLAKE2b-256 379641393d6b033c7600e31129ba810c202776c1aa99ff120e71af38e5da4893

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.5-cp313-cp313-macosx_15_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp313-cp313-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 133749b14869fc5a93d1d6aae7865e93086d6647da0a65496065799306c23df9
MD5 a4eb7c3fb1c125ddb12885a6cf7cff92
BLAKE2b-256 43066a9aa23e492c3a3edbec89e0b3249e426465f946a3413e68f353aae988cb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 af2033dd341e152e75a8f86f090b56b8cdb042510458efc1f6e9d8af7e0e09b7
MD5 43a6fe83c23f871e916737f1e36edc2a
BLAKE2b-256 d04fa38c3308f5f024fe9d8fee0229bc38c607c7352387015758c1b491b3dc3e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 ff178d97bbe7ed9d3844a28097009700d8959c15a851313cb35944f272a95145
MD5 c2c339109358bcbab38b0a8a1966cde6
BLAKE2b-256 6438418d692e3ce73dd619d54d02f00e10e5e715e03be5aac3d31817759ef5fa

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.5-cp312-cp312-macosx_15_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp312-cp312-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 1c4b33b24d6a830f1bda09a626325d58c8573560dbb21925d68a7cedd6a6a18c
MD5 5258b76fea0ac496c70f44e740132606
BLAKE2b-256 965c99ecb5b587ada15b5da37c21260ffeae94830abed9181406f19c5d0a9013

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 edde4b331f8cbd386394dfa2954e5f63ee32ca847b68c8c4caecf839abd8bad1
MD5 59de6ad2331a3caaccfc5804bfac3dce
BLAKE2b-256 76885d807067a513e9a5371e148d684f44badf00ebdd5707539ea360d0850959

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 08af2a32d3839aeb5fd8358a99eaed7bd3b2a39cae64467e092bc470c32d0f39
MD5 d58c11ed603ef66f94e0ddf8ac7b4488
BLAKE2b-256 5278921e7dc1b24644c45628636d92f6431fa102533077d19ff182e548211438

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.5-cp311-cp311-macosx_15_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp311-cp311-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 c66e50c68f46a877df9bb6878a444e82268677f4e9646174c32602a5a2f4f395
MD5 e13d2ae8e48dddeddecbce4de98d8c87
BLAKE2b-256 6d414b7f9dc1d18a79ff2c4f85d0fc4d092ec609406d3cbd8d8235e9d886bf36

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 1bf794a6b019b87ec537ed2632eb24b9b32175e8490501722923681c1e907d53
MD5 71971562958d7817601e56a52093d80b
BLAKE2b-256 e0f31bab28b9a63cca312b7e9848ddc6439db63fc5664e90ff8492ec809bf38d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 92a5fb92af20edfa9596b49dbd3f90fe7f7e7e16ba1d8aefe22ea3f7e8ec067b
MD5 e458443a2d719e444f0b98b9372caf12
BLAKE2b-256 0534032d03f6ae946f45f05f8b6ddde3f09327c429df8d37bf6758e87ab300c8

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2026.6.5-cp310-cp310-macosx_15_0_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.5-cp310-cp310-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 07c60ca1364d3fbace59911021be48b9021d3c3b7772149906815c7af5518659
MD5 58314056d100083f863490e43ea384d1
BLAKE2b-256 fbbd038045c719c540d9c4e1190e7df0f7cc765d2dd4f47a1c7db5df5a4b2fe9

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