Skip to main content

No project description provided

Project description

Docs - GitHub.io Benchmarks Python version GitHub license pypi version pypi nightly version Downloads Downloads codecov circleci Conda - Platform Conda (channel only)

TensorDict

Installation | General features | Tensor-like features | Distributed capabilities | TensorDict for functional programming using FuncTorch | Lazy preallocation | Nesting TensorDicts | TensorClass

TensorDict is a dictionary-like class that inherits properties from tensors, such as indexing, shape operations, casting to device or point-to-point communication in distributed settings.

The main purpose of TensorDict is to make code-bases more readable and modular by abstracting away tailored operations:

for i, tensordict in enumerate(dataset):
    # the model reads and writes tensordicts
    tensordict = model(tensordict)
    loss = loss_module(tensordict)
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

With this level of abstraction, one can recycle a training loop for highly heterogeneous task. Each individual step of the training loop (data collection and transform, model prediction, loss computation etc.) can be tailored to the use case at hand without impacting the others. For instance, the above example can be easily used across classification and segmentation tasks, among many others.

Features

General

A tensordict is primarily defined by its batch_size (or shape) and its key-value pairs:

>>> from tensordict import TensorDict
>>> import torch
>>> tensordict = TensorDict({
...     "key 1": torch.ones(3, 4, 5),
...     "key 2": torch.zeros(3, 4, 5, dtype=torch.bool),
... }, batch_size=[3, 4])

The batch_size and the first dimensions of each of the tensors must be compliant. The tensors can be of any dtype and device. Optionally, one can restrict a tensordict to live on a dedicated device, which will send each tensor that is written there:

>>> tensordict = TensorDict({
...     "key 1": torch.ones(3, 4, 5),
...     "key 2": torch.zeros(3, 4, 5, dtype=torch.bool),
... }, batch_size=[3, 4], device="cuda:0")
>>> tensordict["key 3"] = torch.randn(3, 4, device="cpu")
>>> assert tensordict["key 3"].device is torch.device("cuda:0")

Tensor-like features

TensorDict objects can be indexed exactly like tensors. The resulting of indexing a TensorDict is another TensorDict containing tensors indexed along the required dimension:

>>> tensordict = TensorDict({
...     "key 1": torch.ones(3, 4, 5),
...     "key 2": torch.zeros(3, 4, 5, dtype=torch.bool),
... }, batch_size=[3, 4])
>>> sub_tensordict = tensordict[..., :2]
>>> assert sub_tensordict.shape == torch.Size([3, 2])
>>> assert sub_tensordict["key 1"].shape == torch.Size([3, 2, 5])

Similarly, one can build tensordicts by stacking or concatenating single tensordicts:

>>> tensordicts = [TensorDict({
...     "key 1": torch.ones(3, 4, 5),
...     "key 2": torch.zeros(3, 4, 5, dtype=torch.bool),
... }, batch_size=[3, 4]) for _ in range(2)]
>>> stack_tensordict = torch.stack(tensordicts, 1)
>>> assert stack_tensordict.shape == torch.Size([3, 2, 4])
>>> assert stack_tensordict["key 1"].shape == torch.Size([3, 2, 4, 5])
>>> cat_tensordict = torch.cat(tensordicts, 0)
>>> assert cat_tensordict.shape == torch.Size([6, 4])
>>> assert cat_tensordict["key 1"].shape == torch.Size([6, 4, 5])

TensorDict instances can also be reshaped, viewed, squeezed and unsqueezed:

>>> tensordict = TensorDict({
...     "key 1": torch.ones(3, 4, 5),
...     "key 2": torch.zeros(3, 4, 5, dtype=torch.bool),
... }, batch_size=[3, 4])
>>> print(tensordict.view(-1))
torch.Size([12])
>>> print(tensordict.reshape(-1))
torch.Size([12])
>>> print(tensordict.unsqueeze(-1))
torch.Size([3, 4, 1])

One can also send tensordict from device to device, place them in shared memory, clone them, update them in-place or not, split them, unbind them, expand them etc.

If a functionality is missing, it is easy to call it using apply() or apply_():

tensordict_uniform = tensordict.apply(lambda tensor: tensor.uniform_())

Distributed capabilities

Complex data structures can be cumbersome to synchronize in distributed settings. tensordict solves that problem with synchronous and asynchronous helper methods such as recv, irecv, send and isend that behave like their torch.distributed counterparts:

>>> # on all workers
>>> data = TensorDict({"a": torch.zeros(()), ("b", "c"): torch.ones(())}, [])
>>> # on worker 1
>>> data.isend(dst=0)
>>> # on worker 0
>>> data.irecv(src=1)

When nodes share a common scratch space, the MemmapTensor backend can be used to seamlessly send, receive and read a huge amount of data.

TensorDict for functional programming using FuncTorch

We also provide an API to use TensorDict in conjunction with FuncTorch. For instance, TensorDict makes it easy to concatenate model weights to do model ensembling:

>>> from torch import nn
>>> from tensordict import TensorDict
>>> from tensordict.nn import make_functional
>>> import torch
>>> from torch import vmap
>>> layer1 = nn.Linear(3, 4)
>>> layer2 = nn.Linear(4, 4)
>>> model = nn.Sequential(layer1, layer2)
>>> # we represent the weights hierarchically
>>> weights1 = TensorDict(layer1.state_dict(), []).unflatten_keys(".")
>>> weights2 = TensorDict(layer2.state_dict(), []).unflatten_keys(".")
>>> params = make_functional(model)
>>> assert (params == TensorDict({"0": weights1, "1": weights2}, [])).all()
>>> # Let's use our functional module
>>> x = torch.randn(10, 3)
>>> out = model(x, params=params)  # params is the last arg (or kwarg)
>>> # an ensemble of models: we stack params along the first dimension...
>>> params_stack = torch.stack([params, params], 0)
>>> # ... and use it as an input we'd like to pass through the model
>>> y = vmap(model, (None, 0))(x, params_stack)
>>> print(y.shape)
torch.Size([2, 10, 4])

Moreover, tensordict modules are compatible with torch.fx and torch.compile, which means that you can get the best of both worlds: a codebase that is both readable and future-proof as well as efficient and portable!

Lazy preallocation

Pre-allocating tensors can be cumbersome and hard to scale if the list of preallocated items varies according to the script configuration. TensorDict solves this in an elegant way. Assume you are working with a function foo() -> TensorDict, e.g.

def foo():
    tensordict = TensorDict({}, batch_size=[])
    tensordict["a"] = torch.randn(3)
    tensordict["b"] = TensorDict({"c": torch.zeros(2)}, batch_size=[])
    return tensordict

and you would like to call this function repeatedly. You could do this in two ways. The first would simply be to stack the calls to the function:

tensordict = torch.stack([foo() for _ in range(N)])

However, you could also choose to preallocate the tensordict:

tensordict = TensorDict({}, batch_size=[N])
for i in range(N):
    tensordict[i] = foo()

which also results in a tensordict (when N = 10)

TensorDict(
    fields={
        a: Tensor(torch.Size([10, 3]), dtype=torch.float32),
        b: TensorDict(
            fields={
                c: Tensor(torch.Size([10, 2]), dtype=torch.float32)},
            batch_size=torch.Size([10]),
            device=None,
            is_shared=False)},
    batch_size=torch.Size([10]),
    device=None,
    is_shared=False)

When i==0, your empty tensordict will automatically be populated with empty tensors of batch-size N. After that, updates will be written in-place. Note that this would also work with a shuffled series of indices (pre-allocation does not require you to go through the tensordict in an ordered fashion).

Nesting TensorDicts

It is possible to nest tensordict. The only requirement is that the sub-tensordict should be indexable under the parent tensordict, i.e. its batch size should match (but could be longer than) the parent batch size.

We can switch easily between hierarchical and flat representations. For instance, the following code will result in a single-level tensordict with keys "key 1" and "key 2.sub-key":

>>> tensordict = TensorDict({
...     "key 1": torch.ones(3, 4, 5),
...     "key 2": TensorDict({"sub-key": torch.randn(3, 4, 5, 6)}, batch_size=[3, 4, 5])
... }, batch_size=[3, 4])
>>> tensordict_flatten = tensordict.flatten_keys(separator=".")

Accessing nested tensordicts can be achieved with a single index:

>>> sub_value = tensordict["key 2", "sub-key"]

TensorClass

Content flexibility comes at the cost of predictability. In some cases, developers may be looking for data structure with a more explicit behavior. tensordict provides a dataclass-like decorator that allows for the creation of custom dataclasses that support the tensordict operations:

>>> from tensordict.prototype import tensorclass
>>> import torch
>>>
>>> @tensorclass
... class MyData:
...    image: torch.Tensor
...    mask: torch.Tensor
...    label: torch.Tensor
...
...    def mask_image(self):
...        return self.image[self.mask.expand_as(self.image)].view(*self.batch_size, -1)
...
...    def select_label(self, label):
...        return self[self.label == label]
...
>>> images = torch.randn(100, 3, 64, 64)
>>> label = torch.randint(10, (100,))
>>> mask = torch.zeros(1, 64, 64, dtype=torch.bool).bernoulli_().expand(100, 1, 64, 64)
>>>
>>> data = MyData(images, mask, label=label, batch_size=[100])
>>>
>>> print(data.select_label(1))
MyData(
    image=Tensor(torch.Size([11, 3, 64, 64]), dtype=torch.float32),
    label=Tensor(torch.Size([11]), dtype=torch.int64),
    mask=Tensor(torch.Size([11, 1, 64, 64]), dtype=torch.bool),
    batch_size=torch.Size([11]),
    device=None,
    is_shared=False)
>>> print(data.mask_image().shape)
torch.Size([100, 6117])
>>> print(data.reshape(10, 10))
MyData(
    image=Tensor(torch.Size([10, 10, 3, 64, 64]), dtype=torch.float32),
    label=Tensor(torch.Size([10, 10]), dtype=torch.int64),
    mask=Tensor(torch.Size([10, 10, 1, 64, 64]), dtype=torch.bool),
    batch_size=torch.Size([10, 10]),
    device=None,
    is_shared=False)

As this example shows, one can write a specific data structures with dedicated methods while still enjoying the TensorDict artifacts such as shape operations (e.g. reshape or permutations), data manipulation (indexing, cat and stack) or calling arbitrary functions through the apply method (and many more).

Tensorclasses support nesting and, in fact, all the TensorDict features.

Installation

With Pip:

To install the latest stable version of tensordict, simply run

pip install tensordict

This will work with Python 3.7 and upward as well as PyTorch 1.12 and upward.

To enjoy the latest features, one can use

pip install tensordict-nightly

With Conda:

Install tensordict from conda-forge channel.

conda install -c conda-forge tensordict

Citation

If you're using TensorDict, please refer to this BibTeX entry to cite this work:

@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}
}

Disclaimer

TensorDict is at the beta-stage, meaning that there may be bc-breaking changes introduced, but they should come with a warranty. Hopefully these should not happen too often, as the current roadmap mostly involves adding new features and building compatibility with the broader PyTorch ecosystem.

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

tensordict_nightly-2023.11.16-cp311-cp311-win_amd64.whl (229.3 kB view details)

Uploaded CPython 3.11 Windows x86-64

tensordict_nightly-2023.11.16-cp311-cp311-macosx_10_9_universal2.whl (288.8 kB view details)

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

tensordict_nightly-2023.11.16-cp310-cp310-win_amd64.whl (228.8 kB view details)

Uploaded CPython 3.10 Windows x86-64

tensordict_nightly-2023.11.16-cp310-cp310-macosx_10_15_x86_64.whl (230.6 kB view details)

Uploaded CPython 3.10 macOS 10.15+ x86-64

tensordict_nightly-2023.11.16-cp39-cp39-win_amd64.whl (228.5 kB view details)

Uploaded CPython 3.9 Windows x86-64

tensordict_nightly-2023.11.16-cp39-cp39-macosx_11_0_x86_64.whl (230.7 kB view details)

Uploaded CPython 3.9 macOS 11.0+ x86-64

tensordict_nightly-2023.11.16-cp38-cp38-win_amd64.whl (228.7 kB view details)

Uploaded CPython 3.8 Windows x86-64

tensordict_nightly-2023.11.16-cp38-cp38-macosx_11_0_x86_64.whl (230.5 kB view details)

Uploaded CPython 3.8 macOS 11.0+ x86-64

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 8b19ea1e7af970000da1d8121f976e4b27ea59189c28130a86ec454584d53d68
MD5 01f756ad82db5df99b506fee679e6791
BLAKE2b-256 91ab06df4fb920da3d485dde2d7af2998de35533c5f07acd42430d6aca0268a7

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp311-cp311-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 9172512a9c6afc5964a11850e9a27a1fdb525b833128a2c622cb8c0aac8aced2
MD5 667fba0f032733f7c233a768baa329bb
BLAKE2b-256 ce163f3b1a481f97a03c14bac14b8247e5545e0d5d70133b4524cafd2d1b804b

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2023.11.16-cp311-cp311-macosx_10_9_universal2.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp311-cp311-macosx_10_9_universal2.whl
Algorithm Hash digest
SHA256 06e66716e3f7afaaf8d407d1404c8c6f7898d59befcd5a0b635aadd85d2e3a32
MD5 b2b906e724acf60f68373d54fafefd2c
BLAKE2b-256 32e6ad3c343fb0f37677e9fca47ef89b750bd9012b3362062c481b8124d2c4c0

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 1a5178b049adb04ac47f496b154a9e354952f6b7779ba8f727122ba1d050a75b
MD5 2345ea92dbc8f451cce07ecbdf552194
BLAKE2b-256 7cb8b8b7af96024ee883acb67745a4f72b37c4ddd1f4a3deca552165802dd217

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp310-cp310-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 6b96240f6d685b342b334a0245c0093476a607f2b0eb0dfb9ec526e3c3e3099e
MD5 52dc62f55ad416371a55062ff4eded4f
BLAKE2b-256 60f4014362e36d5dbbf5213f933a99e5982f8f2e555c123c1107853b01d43150

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2023.11.16-cp310-cp310-macosx_10_15_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp310-cp310-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 26c23b0a2b042e71f62f6298e014b367ad5471a0d14d1ba3a1764cdc850712c7
MD5 ffe1b48574f1f081081ac4a56135c8f5
BLAKE2b-256 eb7f0ecfc6e32711fd8e85c7ac2e3170154ca235d1c4c742cf0fa2f4748c4173

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2023.11.16-cp39-cp39-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 f8fe6c6cff468388ed7934f327070d9ad4df8cb54a6c7b599e64a104f838efac
MD5 648e77eb40cb4bf506dd0a5612caf715
BLAKE2b-256 91eb7490eb40d8cb7b2ede32a7ce23234a2138415029d5a35e1e9addcfc7baf2

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2023.11.16-cp39-cp39-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp39-cp39-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 451f1415799afc41f06e0fafc97069217ef6700ed8bc7eb59fe6e9e983121785
MD5 40ec667d3b1b0192b3b24cbd0a9aae6f
BLAKE2b-256 615ce1d79241da195b71a4ba76ebb71c8e11e281ded5ffd672d09afec43a24d8

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2023.11.16-cp39-cp39-macosx_11_0_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp39-cp39-macosx_11_0_x86_64.whl
Algorithm Hash digest
SHA256 a31b2c677459016bfee8fef94765f098b9d851fb1904bf35382ff6ade8c9172b
MD5 aa205d61e88fd6c49d57acbd1fc31506
BLAKE2b-256 debf86b0068c877bdf0726586643b9ce2909886260ca634b92dbb3384e1eaa23

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2023.11.16-cp38-cp38-win_amd64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp38-cp38-win_amd64.whl
Algorithm Hash digest
SHA256 4e1e3d0e3057254e629a2f546fc85c651bdbedc4d2101c9fbf4da0c0b93a1d41
MD5 ffb7ec04de8aa3a26bba62bf85a0339f
BLAKE2b-256 a29a3abe72ecc8c1e02b62b2f88e79af675acc3d8004f566430d1c3e7fed66d3

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2023.11.16-cp38-cp38-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp38-cp38-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 7d915bd403240105d45fcc54ee48172affebc5b22aa7d4ac115b885ede3999b6
MD5 73a5ea5f379786a9950678eecece615c
BLAKE2b-256 4cba0c692554768a58caadf79f98c72bf5811ffe3191af6c505628ed8d618ba4

See more details on using hashes here.

File details

Details for the file tensordict_nightly-2023.11.16-cp38-cp38-macosx_11_0_x86_64.whl.

File metadata

File hashes

Hashes for tensordict_nightly-2023.11.16-cp38-cp38-macosx_11_0_x86_64.whl
Algorithm Hash digest
SHA256 760cd356f487e267faa1434ac812217c67aeab8e30d9617e8812b17bb0c0129e
MD5 3c46ff316c169cb8002de6e46b559154
BLAKE2b-256 a2230055ba60b98823f211935db171400b7f974a65add49b1c43f4b56e9feab1

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page