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

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.6.9-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.9-cp313-cp313-win_amd64.whl (613.2 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.6.9-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.9-cp312-cp312-win_amd64.whl (613.1 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.6.9-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.9-cp311-cp311-win_amd64.whl (611.9 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.6.9-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.9-cp310-cp310-win_amd64.whl (609.9 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.6.9-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.9-cp314-cp314-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 3a2e451c2ad70b4b66e1b721a1b57b1a8634d824b9b229f6750620623b9b4206
MD5 dd7911246b8086972304645048b7c175
BLAKE2b-256 927c4632077d66d75f78b740f8d4033b6ba49b5c03273983e977f9186800a81b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 93691bb518a728a6f26b40ab3928d3a386b025053792366bb9cc73d95fe36585
MD5 afad2942fea9d615c7177571f80893a2
BLAKE2b-256 681b3592ee34948a24fd4e03d98bf224a22e6cfecbe9a1511b9fb52b1e53db71

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp314-cp314-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 a2249d1a58d2e24b52991e8744cbce1386e474dff7a04080121172f195ac74af
MD5 87a64c43b5062692533da76bac917368
BLAKE2b-256 43b5b6152a68345e445ad9a96b39e3c7bf78bfbf8e66c75e10bbf894d96ab458

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 b12931d69feebc1ba34bd64402a621c2f7efb490e7edeac6aed65c9d5c28ce32
MD5 0108df4ee023b7f3251efeeaea2bc8d7
BLAKE2b-256 6027627ebcd87052b66c31b3dac7c960b486d7aeab4a6a0cbf5a34658be25cdb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 200edc1f7afb94a19ea4fa2471a853574c18e9d7574da5e820ecc5b8fb155254
MD5 af92652c257dba84a95b7744fb0cb1fb
BLAKE2b-256 78c7fc0e67d0148efefd8d7e61e0914cf8073d8638bfc6bf536f89427e7f2328

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp313-cp313-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 6a76ff6e6176f22b71a1296cff7e2439ba805a641991506fecfd319181b46870
MD5 62b9f43fa5d876831f91e5a0de566401
BLAKE2b-256 a7cc2b455f8238deaba30cf893951d33fb52ed2add9f2d346cb8a542848a7d5b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 b81b54a1e8f60d06eec096f0b855f76edadecdc437efbffe2bc4fd203950bec9
MD5 b901ea9dc0b94ffeef7faba23b0d6f21
BLAKE2b-256 e7607887979ba2319fe9041823ee220fea28409ec394628f040a865398650260

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 0adffc66936d74d565ce327687689a6d656e56d4df21603b1c7298be424ee4ec
MD5 f272d09330e1d0312d4fb2f46051b763
BLAKE2b-256 2b15249be784ab063824f32577ea1380df27f0d905d007a6fee51fa22e293a69

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp312-cp312-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 b097347d1e56efece0e40b8a0903da070e73c5290fffd20f80119c0066f1fa8c
MD5 70c66856649b3a680c18aab8b1eeb3b9
BLAKE2b-256 f715c2e681ce56b587a006d2f3e0aaa512e5f2e719de85da650256a7aa30e61f

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 c7c2dbdec77d8e3082918294b0f13536c775a09241334df3ab387bc7e3d646db
MD5 9bb727697cdfb2234eaae5dafca4e3df
BLAKE2b-256 63b4ddd1c3844745b8b56431cafc295c850d0211205bc39d5b09226cce452c5e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 9b635550ca9cec32bb8f74026a93bb6f19a128cb62773793f4cf08ac343ef52a
MD5 ea6427e6ea4bc4d43a1d5dca01d7680c
BLAKE2b-256 880f2ff2ece673d08ae2418cc845f98d4a6acd5d38cf4cf9c1491753cf02d5e1

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp311-cp311-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 1deb17d14422e7e39e1d23774ba75c1404a8c1c18129176dfb5ec1acb6a7d6d1
MD5 ce48682cb9c20daab85ecc339e5979c5
BLAKE2b-256 3eda362b01501847d51ed9a3d67d774e66a7acbd1d95303b15d8f11043dbbd66

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 ef199b029ee5c232f16f31847c5d378bb27f45a68da715c9d1827779f9907d22
MD5 00e969ac2a96816ef072cb0906f00376
BLAKE2b-256 e2417430375c675096ee471ed9aae4af9b59730036e5e0f9be7adab826f3fa60

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 fe026ada198c14bba9ebac7f5a8ff266066e8ea3562fd11cca2289449d70bea0
MD5 08eb5ea7027233227e405b7d0fd5d7d9
BLAKE2b-256 775de8e4a361b454b25be999a64351d8586cc0bb27e6efae5d8d328a30b8e182

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.9-cp310-cp310-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 636883404e8fa7da319b37317dc9d00a42dc71b6303a25d17d0c98f5e33f5caa
MD5 f596a7beaa2ab7275e56014b89b9cca9
BLAKE2b-256 3e6747af34d84937d1656f2bbf687d0be65862537a0c61132f7ba2a30d2390c1

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