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

Uploaded CPython 3.14Windows x86-64

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

Uploaded CPython 3.13Windows x86-64

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

Uploaded CPython 3.12Windows x86-64

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

Uploaded CPython 3.11Windows x86-64

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

Uploaded CPython 3.10Windows x86-64

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 8b871ad8ec52c6bbfeb18c3814836ce3530986d774ce89e2e815771f89f95d01
MD5 7ea3b308a70f74977f270a6fde1ce9bc
BLAKE2b-256 d4629767b67dc9e920d2b2883f0344fa5440723bb4a58af27bc78ff361ca42d5

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 9ae297e2d146cf2c2a68f853ee813a4da7a8c41ce3b9ef6e1cf81fab0b8399e2
MD5 54cbfadd2a703a7a22b8b0d1be443187
BLAKE2b-256 78a761afcb6796eacbe14f4c45dc45cda21e9b03eaf9baee5adc7691958c1278

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp314-cp314-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 4d96b2f70e458b5453c734f7aee6db9aa4dc34a857d31647788ad6225fff587a
MD5 5963e0a5500b7c357eb6a8256eb073d9
BLAKE2b-256 39fe0cd3db5fede6310d0da044268e379a24ddf7a6fcefa7e5376b34491f802c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 464f647c8207a4334891024c5d1555295333d9b58886b83ada18278888365863
MD5 1daaed1c77ecdadd1bfd75c1d7af2035
BLAKE2b-256 1c70e71ca2e2383b0e8157727aff2f7d0043f70baa7ab276627d9fe902429526

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 cfc7f932368cc9b809040ddbc345cc415da630203359840de4c9a4f83ef2bda7
MD5 e8b925e3d9dd3c3b419b99f339b3094e
BLAKE2b-256 cf4c1f55dcdeb2a8f2123cf0c5863e4208b9ebf1bcace076ddb003074d385349

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp313-cp313-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 a9646e7254fd57832c53b2b65031631457ee5f9123614227fa0f72cd680ea76a
MD5 5e8fdc4257fa3a885ce27c1cda0e5047
BLAKE2b-256 3592ebf4818d3f17e9cbc67232d94620d1005461f572d94af69e5b657e5f9ead

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 ee3db587e9f0fc4beb873069938b79d284dc6520e2bfd1aaf446b47f1f84a90a
MD5 39306a92b82b203520bb8fadc761200e
BLAKE2b-256 232be4a379821de7311e53e9b31e9e376ae103bb78f0632e4161e3aa67c634ef

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 18bb594ea3ce349b038c3c3bd7538d91769163613d8820edbc963d55bd292219
MD5 abf0a8add3e0f1e76ade4481ca54d344
BLAKE2b-256 5ef592d880510dc4ad04ba9fed90567a8c1bdac75911732c20b9ee226020ba94

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp312-cp312-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 e5e2d00ec166459069e7ea839c897cad38b8d1d33e8a161f8ecd42b57c0bcaaa
MD5 132cb27dd56a1208a0c96dc1ea7a6905
BLAKE2b-256 fdbf0c78ab6d530492a43e477c36fa766c6582a88762e6aaece8b0a93741c6cc

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 d992daacfeffc56d6d2418231ea76a0ae9ed230e4fba43e7046508f1a326a387
MD5 87754e818cf8c711a7230ed8d181d6b6
BLAKE2b-256 b689812bfba4b1dee155e0fb5c90de573a27def3906a91313f8364f5ebbf7c4d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 37a6042f808b051bc03ca0a4aa909cd2d82145ebb27c4d028faa8776e608ce0c
MD5 73382d68a1fdd1ba9e1f3a9de8043fe7
BLAKE2b-256 db397a92bc1d748530707874da1c118ca50bc70bb87acca52d2d96042fd21564

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp311-cp311-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 599374eb094b7bd6d4d29a139019b94d1c251caee9bac69a1378a7a90586939e
MD5 688c1141752128b349518e6656b45823
BLAKE2b-256 3f17006192d64f6d2bc7b1bcfabcc767327f22631e3804bac04671945c8960e5

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 fafbd49014db61ade5128f88eca7eb872d6b4c585b404459b187653a5e76f839
MD5 7de33912487d9d54b3ecb4941ca55eff
BLAKE2b-256 9694a6adc7c5b808cd8a05fdabdc541ec3f83fe41df7e53482d20d5bd3fe11fd

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 92a69d55552d65f23f908ef7e1f73e384706367ee717c13b024538352e498565
MD5 7bda00f70d43a6b45e48d0a17cd85464
BLAKE2b-256 ebdd1fd825110fc95b7ae9c06a6f78e3ffca3d3fddfd66073cbb6f7211fd80ec

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.7-cp310-cp310-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 101a928a550dd845db98f02cb615e33bddf32bc05b7be9624cfc96368b227aeb
MD5 d57093041b2b0e22fc879879cdfb0902
BLAKE2b-256 fbbe224800d3d3b00b0e4e5e64ac9637844a29187113c4a9a505c0a22e81fdc3

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