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

Uploaded CPython 3.14Windows x86-64

tensordict_nightly-2026.7.3-cp314-cp314-macosx_11_0_universal2.whl (549.2 kB view details)

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

tensordict_nightly-2026.7.3-cp313-cp313-win_amd64.whl (623.3 kB view details)

Uploaded CPython 3.13Windows x86-64

tensordict_nightly-2026.7.3-cp313-cp313-macosx_11_0_universal2.whl (551.7 kB view details)

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

tensordict_nightly-2026.7.3-cp312-cp312-win_amd64.whl (623.2 kB view details)

Uploaded CPython 3.12Windows x86-64

tensordict_nightly-2026.7.3-cp312-cp312-macosx_11_0_universal2.whl (551.7 kB view details)

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

tensordict_nightly-2026.7.3-cp311-cp311-win_amd64.whl (621.5 kB view details)

Uploaded CPython 3.11Windows x86-64

tensordict_nightly-2026.7.3-cp311-cp311-macosx_11_0_universal2.whl (550.8 kB view details)

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

tensordict_nightly-2026.7.3-cp310-cp310-win_amd64.whl (618.5 kB view details)

Uploaded CPython 3.10Windows x86-64

tensordict_nightly-2026.7.3-cp310-cp310-macosx_11_0_universal2.whl (548.9 kB view details)

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

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 e95bfab247c11a03a6e1e94df1ea1b2f1351aafc987683a0341eeba30f468b70
MD5 2caf8229dee2cfe5a369c1ba7427293e
BLAKE2b-256 7b1886788b8420279289b604c81f95651f5e6ee8fce8ccd483a1c7d50d263b7d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp314-cp314-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 13e112a370525284402d387cabe02372932ec45d411a6a76f7f522834eec8696
MD5 221db7038a6e0959fcd7af49907b9086
BLAKE2b-256 70779f80886a1a40cb479ce144f3e865cc87f85c7abaa64d9baf2ccb6e41a290

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp314-cp314-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 bc85c5c3fea91a93094fb2d4f0303a5de56725c60a0edd116bb32ede1fcfcf19
MD5 d5a565510787b0e34e81b2cb7cc04167
BLAKE2b-256 75e605feb6522d2abdb353636dfdb3718c3b55cfbebac5a10ae555349c5d5494

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 f8c7cf3475f65dd1a8ea5f48160c224d156480a7fd5078061ddce506b9454b6e
MD5 e57c7ed452d6b43ab00e7cdeebf9d9b7
BLAKE2b-256 5dd280b0fde093a85dbb6c8d4a7a7dc173fc6e089627c6b048953d6830506c70

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp313-cp313-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 18746f73346f6eb4bd79b951a0be78ff46c192ef4f6fce7c1253d2cc90a03baf
MD5 987c194cd5c36b3a40aebc5862e32308
BLAKE2b-256 14ae0535d84e46099882c18a4f2af6e87bf1189d0866e2ec43f451b55e342219

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp313-cp313-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 387048d5617f4820cfd8fa603966d275449e833b00414ce126adcb34186389b0
MD5 cc4c87d56a59502d91cdba292cb3d261
BLAKE2b-256 bdfc08f62e4abe41cd477dcedfd5ccccc929094938acbaa82089e89966af8ffe

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 b412bd9d6a11b1dd6ae5ec6f385f9c22455c59f561726f7b2a85e8c4eab96948
MD5 5384a66682b8b95e85d4b17b55f1b0b7
BLAKE2b-256 0de36956efeb5b59ca9fcf74822bf79aea53412653f78dfdf3dfe1412e20bed4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp312-cp312-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 eeb2d0d4720db0d16a085f444aaa79d641ff2864367254207538d04de81023bf
MD5 0b7947b93ee81e2683e8cebcd96d947d
BLAKE2b-256 fd0778f6f32b6b2ab62d7223ddb398e612a51b6e3d4f5ec09d350095c2e83c55

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp312-cp312-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 d0b8d31ed466c7735aea5f8af05fd970bf8468502ea690fd507c9074ea03a90b
MD5 6b9cb91a919b7f41b39e1883bbdf14bb
BLAKE2b-256 b2d33cb772cd02b6d550c9bbdeba6234d4875862c00c9bc0977d282e6839c11c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 606a9c10191b55f62f8d23ec8514273c94acfe1b0c8e28d4f4fbc1c6d8d6e423
MD5 7f571cc9e2690905417ff8be5cbd3d07
BLAKE2b-256 335fde14eaf54af954ef70af28ab3a0daccb1fdf646fc90aaa2f2d75e5527300

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 e33b264ca89cb172adc4868833e6cd01c530bbe324274e60c47ef37c09397884
MD5 10b6da3b5980be411fe1a0151942d803
BLAKE2b-256 bea3c06baf8fbce3f205cc9b09118e044e5a5db55b12b5acbd80d6aeb15fa613

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp311-cp311-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 9d94383d156389bf3c1f8e21b7c1b23946e803fafedf5a297456e3486290cae1
MD5 702660b4df532edc6c385df08063d510
BLAKE2b-256 7aaed662aa54b84f560a3750cf4fe998ff933a09402cb0c02391a209b99ffb66

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 38087e1a081d0037835935df8f36dad889dab6fe74399f500f8c2a0d0e3d4843
MD5 dc1b7916b76347da15f831397b6d4112
BLAKE2b-256 69c140678fe7f7ed4635691802d2d4c932214199459cc38e5bab7385c9380cc7

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 a0534ba9e15505e08782d0bc81a7c9d47c94eac575242c86eb614ea383f6445a
MD5 2a04b3fe5cbc414f04730bce59401e02
BLAKE2b-256 4bb7e84bd8ec50edb2a22bd69791be36ffcf8128f378ffa8728a8c1a5eee3986

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2026.7.3-cp310-cp310-macosx_11_0_universal2.whl
Algorithm Hash digest
SHA256 11ce4ef72a3a3595875c6e7cac024d14b636dbafac504976752878bfecaa3164
MD5 203d379afa5f5245b7ea8fb5918dfb23
BLAKE2b-256 1389909858c333f394dd1168148ca1e7f0ddcd40b101a3b66469c6e7cc721415

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