Skip to main content

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.

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

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.7.24-cp314-cp314-macosx_11_0_universal2.whl (574.8 kB view details)

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

tensordict_nightly-2026.7.24-cp313-cp313-win_amd64.whl (646.3 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.7.24-cp313-cp313-macosx_11_0_universal2.whl (574.6 kB view details)

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

tensordict_nightly-2026.7.24-cp312-cp312-win_amd64.whl (646.2 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.7.24-cp312-cp312-macosx_11_0_universal2.whl (574.6 kB view details)

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

tensordict_nightly-2026.7.24-cp311-cp311-win_amd64.whl (644.6 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.7.24-cp311-cp311-macosx_11_0_universal2.whl (573.8 kB view details)

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

tensordict_nightly-2026.7.24-cp310-cp310-win_amd64.whl (641.6 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.7.24-cp310-cp310-macosx_11_0_universal2.whl (571.9 kB view details)

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

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 f21b6fb8c85a3798d6d119144c03cc967149dd1c473b83e53903882c4cdc8248
MD5 6832ac96f03db2a352b9b4ebc9fb2d47
BLAKE2b-256 73f1e80ae69eba17512f693008f0d1ebe95b24c6cb1c06f1f02666b48acc1ef9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 430de8d58bfcb0760f7881a4e19b318e3ffa79323ab8c09208eb3bf487be6d46
MD5 2c7028243118e2d47c85f7a4cc868cc6
BLAKE2b-256 b7c6252b61b682016e98f572523c14ba79ddb5f1230ee3c8724f28b82c8090fa

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp314-cp314-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 b26f6fef3223371b229900c6c8e03ee7025a46620c399fae31bb2b5e0e9c99c5
MD5 2e785332765eebe1fbe580cffc34253e
BLAKE2b-256 4323655fd085419a3dab617eb0fbc8f29bf10deae8ca153c5f55b8aecb473317

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 08c5d665414b2ca6c98cba675784458553ccf5c496fa22d9ec5f1c1b387922e7
MD5 6744917a80cfb58afa10a9c38f1c2584
BLAKE2b-256 96ed2d3b4a8d332ff78b2ec36917443fc2a207ed9772a916133a7330c4ef26ed

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 c82884e000bb20c40907f7e69dd871975412fb06a7e5b0b47bbd61dd31c2b77a
MD5 d1c291dd29dab25c5345aca52e7f793a
BLAKE2b-256 75471acc110b5540600bcef3bbce9ffcdba8e4d01e8782e950c56fcde4798e5d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp313-cp313-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 901c9082d814bf49f6716bdeb0f16618911b3101ec15b8acc30afcad80469515
MD5 d2f70e175c52f04cf64c8926d4c7b2e9
BLAKE2b-256 c0e170aa7844f681734fbf9bb9ea3c44c2ca468e7becba47e326b8848815759f

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 bad464b3842f39b9f0564af3384c2e0f62d541eef4b853721e180cf0b3c0f5d1
MD5 9d3ec4000afc551f3997990459f86c81
BLAKE2b-256 a0e7e6eba0efca39a5d294042e1e989b21cbfbb9fd90c73d40aec220b560604f

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 40697bd8d003ca290cb73daed1c7e959aad1fa2de686158ab4689d2e6fd0b9a5
MD5 2429a28d20df8a2286032f5c80711df5
BLAKE2b-256 fed62cd96e2d45cea417f0cea49925072355aadd25c100896e0d07d14f7268b4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp312-cp312-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 347cbea89e4928bdabc4ba4184969e3e671daca9121d5418c0a278889c205719
MD5 5ffe19ee58d08a3210c12e1625609fc3
BLAKE2b-256 7cf2367c44707f70e1ebdbf512c0adf609ffc5c04818e9ddcb7b83805a0dc4ec

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 ba72d31055018d38019756cafc78f3d793282b78b7f322c9ca6654ae9c87cc75
MD5 271a4d7cf7df85c22a726fa7c19a7404
BLAKE2b-256 ccdc174c1392304a72cb299131bd3f2e53f8330f79b2185e355c736c8b7ef9c2

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 7024251db5f7351214e9e4b284d0a893a9d2b547bf73f77119002c2c740d361a
MD5 782e9f76b9fc978c970366f83bfd68d3
BLAKE2b-256 ed5a4d215aa692493985dd7e42fbdee9696ee2244091f2c5fe2be1f08dcf9a10

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp311-cp311-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 88d1e0f29c634cddb04eb7647dabbbf028c0dbc88da46327ff3307423434b01e
MD5 caeadd94d971f03bc35187a6e17d7906
BLAKE2b-256 f0b66cecdd1ba0e9a3130c10990d430831a665c8174086ba60f6bde9371d573b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 8c1c6d7b84ee2102659257a7826738bde3b5eb222d5685b3827704fbed95c479
MD5 64f5536e3939de86001e93f479e1ab2f
BLAKE2b-256 9e954e2bc794fe8e0764194119200ff59721a13cc66060fca4d8e2c08fc96888

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 6112fef8677476b1aefec452e24213ae31b006106d6f26ef4af28222c7a71b5c
MD5 195dcd2923623479b3f6a1318d3e4d97
BLAKE2b-256 855f569f918dc3f792ab12c9e185a1ed654d629eb80a14d1dc8488b07996d795

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.24-cp310-cp310-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 c141ac330ff44343a6f1128780fbdcd1c9173dbd7bd05afe750019c95c8b788d
MD5 28f82d9358ca3f38bc3281fa58f1e25b
BLAKE2b-256 bf52b4e748984053b2eab7d6b6e7191d91372493df6762caaf7558190196c031

See more details on using hashes here.

Release history Release notifications | RSS feed

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page