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

Uploaded CPython 3.14Windows x86-64

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

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.6.10-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.10-cp312-cp312-win_amd64.whl (613.2 kB view details)

Uploaded CPython 3.12Windows x86-64

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

Uploaded CPython 3.11Windows x86-64

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

Uploaded CPython 3.10Windows x86-64

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 2090a7a8a35158aa71f4b5000abfa06db15c09f649e9c9e2fff9e43f7608c129
MD5 9a4c2597b41a1093872a362cc87c6ee0
BLAKE2b-256 0f17cc2f52b03c7cef0cb7b9242322b2d314f089856ceb85617f9b38b4c8e390

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 d609c1c5c3a646d0cc354ccb8371663c58a53835165dca15b7d1df5a3e1c83aa
MD5 f80e65779474b4a45b5db409e9cf8161
BLAKE2b-256 3bfc228009b457b768b53da2f42762cd37fea4c336704480f5bc3afa2824d636

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp314-cp314-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 9b1a9a61b44431872805f44b37a2e13a220d2c4342796668c9bb0bf5f1f9f3cd
MD5 00d335179aa7511ae50ef27eb623977f
BLAKE2b-256 0a8b0be342bc8f62ea99c4f717032a114a6495bee2691ebcd0403fae8cf04f8e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 d8bab35c422f42b9588ff932c90de3baadba48dae7fd69afc200df13b551ff3b
MD5 9101533d637bfbc8e005b17eeba0416d
BLAKE2b-256 28a351620643fe8636aaac8da24be9434005493fbce0879e99d001d197b53dea

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 91274ac05aaf8ad44c6edfb146993203552b3e5721747ad44249cee0672042ed
MD5 e1808940f94648a4861511837147775e
BLAKE2b-256 dee80a1fab6138da130d03b67dd9c1b14d6cc3ba87f5acaedefb109ccbbba021

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp313-cp313-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 ef9b6c67ffc05da276ff3c4e02f62057a5e270c7b3ca79fb3d87711f20eea7dd
MD5 d94868cfb45436603fc829ee70c772cf
BLAKE2b-256 01e6aad470fee5f50604454fab52725c7432c3411dadfd102e06f8411a9ab923

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 6cd44b6b035c87e2f7624f4ed0ea01a1457f897c8575d5bd59601b68c2d85291
MD5 956e9820b59ff920e6f2a5db00beb20c
BLAKE2b-256 525601092e5b47b3e08f89f7ccc213e7fbd5087b19b5ae885c086e9d86ff43da

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 1638b9d276c04d23ad6a7b674d63eca73743dfbdfa2ec50837d9cf9a0c55287d
MD5 75471684fc662d4247477d6c2d3aa985
BLAKE2b-256 69fe70bd52e10c65ec7f0ced0c2c861d7cd3a855476392d5aac6223929b68111

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp312-cp312-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 f879de695725ffcd1eed4487df26c9ec89b37c26be742436275e6c38a6ce7d62
MD5 db96357613602b0d5ab9480df13bc750
BLAKE2b-256 620dcd48a3611928ccb951091227ba3df58ff7352900727b6138f7b110bded16

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 5f2a935d4e3a81afe265ce86bfae1e87fe0e5c65ed757999dcca04a83d27f80b
MD5 ecb1f02e6e32d5907b8f04584d1cd060
BLAKE2b-256 3eb2caf04247acf7d9b8fee97f5cce424a6d6d7eec0a3cef295d550e28581be4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 cdb2f6782d9bb2ce87fdfaef4f5eb372acbecb16f94b98b7960e7e4c6f95ed6a
MD5 723e4363c0f5a5949c21b9844dce6f44
BLAKE2b-256 567da0d44c83fbe336c1d4b10cfc7f784d3620aa24df4939c49b73d63c05987e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp311-cp311-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 3728e58ae5d72609a1be6a5ceb5db44cc9d86c0b1b1a3192ec2130a32697adc4
MD5 a2bac2e49b3890cf70e5b65406137898
BLAKE2b-256 7f2a950b18763c2c7308d7825f6edcd02277333c0cc0e665e560d2de6a92665d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 a6bf6b5d7558b6d06dad9ac9eecccbf53130ecc0e9f8aadc1a16f8b23012ffb1
MD5 049cbb07b1b4c421e13e4dfa5ab06968
BLAKE2b-256 a27e8db7f7600635c99ffcf1a8d8cb504a4cf34ab651ea36f10940c94a3fa255

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 371af6b2d34ce2ce5bf479492d4ff6511943a2da949baed572e3893801794cab
MD5 49681c8f56582cba7f36db268c0c28a6
BLAKE2b-256 a1aab03c31de636e45b2b3f3304b1a1c9c8da0176ecc1d521018c82f80141f73

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.6.10-cp310-cp310-macosx_15_0_universal2.whl
Algorithm Hash digest
SHA256 0f01b2ff9a256adc8c3a8d4d37b3fbb2e2608391f83a1b32e6d3ff0a5c6e837d
MD5 59db9d68f0e0effc96ab048a766be9d1
BLAKE2b-256 9b3f74370984178f6192097130d9862640fd4b5a2f93bd7400eee75e24ac90ce

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