[RFC] torch.dict.TensorDict

username: vmoens
cooked: <h1><a name="rfc-tensordict-1" class="anchor" href="#rfc-tensordict-1"></a>[RFC] TensorDict</h1>
<p><a href="https://github.com/pytorch/pytorch/pull/112441" rel="noopener nofollow ugc">This PR</a> proposes to integrate the core features of <a href="https://github.com/pytorch/tensordict" rel="noopener nofollow ugc">tensordict</a> in torch core under <code>torch.dict</code>.<br>
We welcome comments, contributions and suggestions!<br>
To get a sense of what tensordict can do, you can either install it via PyPI (<code>pip install tensordict</code>) and/or try the PR directly.</p>
<h2><a name="purpose-2" class="anchor" href="#purpose-2"></a>Purpose</h2>
<p>TensorDict is a data carrier for PyTorch. The problem it is trying to solve is to provide a uniform way of <em>carrying</em> more than one tensor in a code base without having to specify beforehand what entry is or is not present in the data structure, and <em>operating</em> on these as a batch.<br>
More specifically, it solves the following problems in pytorch:</p>
<ul>
<li>reduces boilerplate when the same op has to be applied to a batch of tensors (eg, samples from a dataset, parameters from a model)</li>
<li>isolates parameters from a model and enables operations on these independently from the model structure (eg, (a)sync communication, gathering, splitting/sharding etc), essentially decoupling the model (algebraic operations) from the data it operates over (incl. parameters)</li>
<li>better representation (print) of tensor structures</li>
<li>more straightforward functional API</li>
<li>intuitive parameter and data serialization, with efficient indexing via memmap</li>
</ul>
<p>In brief, the goal is to be able to write generic data pipelines (transforms, preprocessing) as well as parameter manipulation (point-to-point communication, serialization, sharding) while avoiding to explicitly loop over the set of tensors that is being provided.</p>
<p>It is based on a couple of <strong>basic rules</strong> (think of it as axioms) from where all other functionalities follow naturally:</p>
<ol>
<li>A TensorDict behaves like a dictionary of tensors / TensorDict instances, as such it allows nesting;</li>
<li>A TensorDict “shape” (or <em>batch-size</em>, in contrast with <strong>feature-size</strong>) is arbitrary, required upon construction and constrains all its content to share the same <code>N</code> first dimensions. This feature allows shape operations and indexing;</li>
<li>TensorDict does not constrain the dtype in any case;</li>
<li>TensorDicts have an optional <code>device</code>. If specified, it will cause all tensors stored in the tensordict to be mapped onto the device.</li>
</ol>
<p>This simple set of rules completely defines TensorDict’s expected behaviour. For instance, given that a TensorDict has a shape, <code>__getitem__</code> supports both key-based and shape-based indexing. The fact that multiple dtypes (as well as the feature size) can be stored and are not checked make the implementation of algebraic operations out-of-scope.<br>
When nesting TensorDicts within each other, the root must always have at least as many matching dimensions as the inner nodes, etc.</p>
<h2><a name="basic-usage-and-concepts-3" class="anchor" href="#basic-usage-and-concepts-3"></a>Basic usage and concepts</h2>
<p>A TensorDict can be created explicitly from a set of tensors or arrays:</p>
<pre><code class="lang-python">data = TensorDict({
   "tensor": torch.zeros(3),
   "from_np": np.zeros((3,)),
   "from_int": 1,
   "from_list": [[1, 2, 3]],
   "from_dict": {"a": 1},
   }, batch_size=[]) # batch-size must always be specified
print(data)
</code></pre>
<p>which results in</p>
<pre><code class="lang-auto">TensorDict(
    fields={
        from_dict: TensorDict(
            fields={
                a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)},
            batch_size=torch.Size([]),
            device=None,
            is_shared=False),
        from_int: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False),
        from_list: Tensor(shape=torch.Size([1, 3]), device=cpu, dtype=torch.int64, is_shared=False),
        from_np: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float64, is_shared=False),
        tensor: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)},
    batch_size=torch.Size([]),
    device=None,
    is_shared=False)
</code></pre>
<p>or directly from a module containing parameters:</p>
<pre><code class="lang-python">net = nn.Sequential(nn.Linear(3, 4))
params = TensorDict.from_module(net)
print(params)
</code></pre>
<p>which results in</p>
<pre><code class="lang-auto">TensorDict(
    fields={
        0: TensorDict(
            fields={
                bias: Parameter(shape=torch.Size([4]), device=cpu, dtype=torch.float32, is_shared=False),
                weight: Parameter(shape=torch.Size([4, 3]), device=cpu, dtype=torch.float32, is_shared=False)},
            batch_size=torch.Size([]),
            device=None,
            is_shared=False)},
    batch_size=torch.Size([]),
    device=None,
    is_shared=False)
</code></pre>
<p>A key concept in <code>TensorDict</code> is <code>NestedKey</code>: a <code>NestedKey</code> is anything from a regular string to a tuple of tuples of strings.<br>
For instance, in the above example, <code>data.get("0")</code>, <code>data.get(("0",))</code> and <code>data.get((("0",),))</code> all return the same value.<br>
The reason we allow nested tuples becomes apparent when we need to append keys one after another: say you want to get the <code>weight</code> in above example, but the code that treats that is only given a prefix which can be a tuple or a string (ie, a <code>NestedKey</code>):</p>
<pre><code class="lang-python">def get_weight(params, prefix):
    return params.get((prefix, "weight))
</code></pre>
<p>Allowing for nested tuples avoids having to check for the <code>prefix</code> (or in other cases suffix) type when concatenating keys.</p>
<h2><a name="features-4" class="anchor" href="#features-4"></a>Features</h2>
<h3><a name="tensor-like-features-5" class="anchor" href="#tensor-like-features-5"></a>Tensor-like features</h3>
<p>Tensor-like features are focused on shape-based operators, device and dtype casting and distributed methods. Algebraic operations are ignored but can still be executed easily with <code>tensordict.apply</code> (see below)</p>
<ul>
<li>shape-based operators: <code>reshape</code>, <code>view</code>, <code>permute</code>, <code>transpose</code>, <code>flatten</code>, <code>unflatten</code></li>
<li>Indexing and masking: <code>__getitem__</code> and <code>__setitem__</code> support all indices supported by <code>torch.Tensor</code>. Masking can be particularily useful:<pre><code class="lang-python">data = TensorDict({"key1": torch.arange(12).view(3, 4, 1)}, batch_size=[3, 4, 1])
mask = torch.zeros(3, 4, dtype=torch.bool).bernoulli_()
data[mask]  # a tensordict of shape [mask.sum(), 1]
</code></pre>
</li>
<li>Augmented torch functions: <code>torch.ones_like</code>, <code>torch.zeros_like</code>, <code>torch.full_like</code>, <code>torch.empty_like</code>, <code>torch.clone</code>, <code>torch.squeeze</code>, <code>torch.unsqueee</code>, <code>torch.masked_select</code>, <code>torch.permute</code>, <code>torch.where</code> and <code>torch.gather</code></li>
<li>Padding: one can pad a single tensordict along the batch-dimensions, but also stack a list of tensordict of different shapes with a certain padding value (see <code>torch.dict.pad_sequence</code>)</li>
<li>Stacking and concatenating: <code>torch.stack</code> and <code>torch.cat</code> have been augmented to work with tensordict instances.</li>
<li>Split, unbind, chunk</li>
<li>Casting: <code>TensorDict.to(...)</code> has the same signature as <code>Tensor.to(...)</code> while also accepting other <code>TensorDictBase</code> subtypes</li>
</ul>
<h3><a name="dict-like-features-6" class="anchor" href="#dict-like-features-6"></a>Dict-like features</h3>
<p>TensorDict comes with many dict-like features:</p>
<ul>
<li><code>get(key, default=some_val)</code> where <code>key</code> is a <code>NestedKey</code> (see above). The default value can be anything, not only a compatible type (tensor or tensordict);</li>
<li><code>pop(key, default=some_val)</code></li>
<li><code>setdefault(key, value)</code></li>
<li><code>del data[key]</code></li>
<li><code>data.rename_key_(key_origin, key_dest)</code></li>
<li><code>data.unflatten_keys(separator=".")</code> which unflattens a tensordict along the key dimension (particularily useful when representing state_dicts: <code>data = TensorDict(module.state_dict(), []).unflatten_keys(".")</code>)</li>
<li><code>data.flatten_keys(separator=".")</code> which flattens a tensordict (particularily useful when one needs to represent parameters as a state_dict)</li>
<li><code>keys</code>, <code>values</code> and <code>items</code> all accept (key)word arguments <code>include_nested</code> and <code>leaves_only</code> (both <code>False</code> by default to match dict behaviour) which will iterate over the sub-tensordicts, potentially ignoring non-tensor (ie, TensorDict) values.</li>
</ul>
<h3><a name="arbitrary-functions-7" class="anchor" href="#arbitrary-functions-7"></a>Arbitrary functions</h3>
<ul>
<li><code>TensorDict.apply</code>: allows you to compute a certain function on all the values of the tensordict (recursively). It accepts other tensordict instances too, allowing the implementation of algebraic operations OOB.</li>
</ul>
<pre><code class="lang-python">data_x.apply(lambda x, y: x+y, data_y) 
data.apply(lambda x: x.norm().cpu(), batch_size=[], device="cpu") # if the device or batch-size change, they can be specified here
</code></pre>
<ul>
<li><code>TensorDict.map</code>: Like HF’s <code>datasets</code> <code>map</code> function, it maps a function over the whole tensordict, across one given dimension:<pre><code class="lang-python">          &gt;&gt;&gt; import torch
          &gt;&gt;&gt; from torch.dict import TensorDict
          &gt;&gt;&gt;
          &gt;&gt;&gt; def process_data(data):
          ...     data.set("y", data.get("x") + 1)
          ...     return data
          &gt;&gt;&gt; if __name__ == "__main__":
          ...     data = TensorDict({"x": torch.zeros(()).expand(1, 1_000_000)}, [1, 1_000_000]).memmap_()
          ...     data = data.map(process_data, dim=1)
          ...     print(data["y"][:, :10])
          ...
</code></pre>
</li>
</ul>
<h3><a name="serialization-8" class="anchor" href="#serialization-8"></a>Serialization</h3>
<p>Disclaimer: Parts of this API is WIP as we’re making individual tensor serialization</p>
<p>One of the goals of tensordict is to get an efficient representation of data on disk, by tracking file name and location, while preserving a fast memmap-based indexing. This allows us to represent huge datasets composed of multiple tensors on disk. If part of the preprocessing can be done anticipatively, this can bring a tremendous speed-up on dataloading:<br>
<img src="https://github.com/pytorch/pytorch/assets/25529882/f730a4e2-cacd-4216-a579-0d700a6ca5b0" alt="image" width="689" height="375"></p>
<p>For parameter serialization, one can do something as simple as</p>
<pre><code class="lang-python">net = nn.Sequential(nn.Linear(3, 4), nn.Linear(4, 4))
params = TensorDict.from_module(net)
params.memmap_(prefix="/path/to/params")
</code></pre>
<p>which will result in the following data structure:</p>
<pre><code class="lang-auto">/path/to/params
│
├── 0
│ ├── weight.memmap
│ └── bias.memmap
│
└── 1
  ├── weight.memmap
  └── bias.memmap
</code></pre>
<p>Currently, these memory-mapped tensors are a subclass of <code>torch.Tensor</code>, but we are looking at a refactoring of this where these are plain tensors.</p>
<p>Food for thoughts and topic for discussion: how should this work with parameter tying (ie, since we copy tensors in one location corresponding to their location in the module, how does this work when the same parameter is present at multiple places within the module?)</p>
<h3><a name="functorch-compatibility-9" class="anchor" href="#functorch-compatibility-9"></a>Functorch compatibility</h3>
<p>TensorDict is compatible with several features from functorch:</p>
<ul>
<li>
<p><a href="https://pytorch.org/docs/stable/generated/torch.vmap.html" rel="noopener nofollow ugc"><code>vmap</code></a>: it is easy to vmap over a TensorDict and the shape is treated in the same way as a Tensor shape:</p>
<pre><code class="lang-python">td = TensorDict({"a": torch.zeros(3, 4, 5)}, batch_size=[3, 4])
ones = torch.ones(4, 5)
td_out = torch.vmap(lambda td, one: td.set("a", td.get("a") + one), in_dims=(0, None), out_dims=(1,))(td, ones)
assert td_out.shape == torch.Size([4, 3]) # the last dim has been swapped, as per `out_dim` argument
</code></pre>
<p>The core of the feature lies in the batch-size preservation of these operations, which requires TensorDict to be registered within the <code>vmap</code>-related functions.</p>
</li>
<li>
<p><a href="https://pytorch.org/docs/stable/generated/torch.func.functional_call.html" rel="noopener nofollow ugc"><code>functional_call</code></a> (WIP): since <code>TensorDict</code> can efficiently represent parameters, it is natural to use it for functional calls with <code>nn.Modules</code>. Unlike the “regular” API, using <code>TensorDict</code> allows to vmap over the parameters in a more natural way (when working with model ensembles):</p>
<pre><code class="lang-python">params = torch.stack([TensorDict.from_module(module1), TensorDict.from_module(module2)], 0)
y = vmap(lambda p, x: torch.functional_call(module1, p, x), (0, None))(params, x) 
</code></pre>
<p>This has the advantage that the parameters are represented with the appropriate shape from the outside. Stacking them or unbinding them comes out-of-the-box and at no cost.<br>
On a low-level, tensordict recursive implementation avoids some overhead (handled by caching of nested modules) when setting parameters in a module, because it will assign the parameters to the modules one at a time by following the strucutre of these much more naturally than a flat dict would. This also makes the implementation (arguably) more straightforward.</p>
</li>
<li>
<p>First-class-dimension: Parts of a TensorDict batch-size can be hidden using <a href="https://github.com/facebookresearch/torchdim" rel="noopener nofollow ugc">first-class-dimension</a>. For example, the example above can be simplified as such:</p>
<pre><code class="lang-python">from functorch import dim as ftdim
params = torch.stack([TensorDict.from_module(module1), TensorDict.from_module(module2)], 0) # params has batch-size [2] 
dim = ftdim.dims(1)
params = params[dim] # params has now an empty batch-size
torch.functional_call(module1, params, x)
</code></pre>
</li>
</ul>
<h3><a name="pytreehttpsgithubcompytorchpytorchblobmaintorchutils_pytreepy-compatibility-10" class="anchor" href="#pytreehttpsgithubcompytorchpytorchblobmaintorchutils_pytreepy-compatibility-10"></a><a href="https://github.com/pytorch/pytorch/blob/main/torch/utils/_pytree.py" rel="noopener nofollow ugc">PyTree</a> compatibility</h3>
<p>Additionally, <code>TensorDict</code> is compatible with <code>pytree</code>. This is aimed at making tensordict interchangeable with regular <code>dict</code>, but it is not used to implement tensordict functions (as they manipulate the batch-size, which has some inherent logic).</p>
<p>When using pytree, the batch-size will be preserved:</p>
<pre><code class="lang-python">        td = TensorDict(
            {
                "a": TensorDict(
                    {
                        "b": TensorDict({"c": torch.ones(2, 3, 4)}, [2, 3]),
                        "d": torch.ones(2),
                    },
                    [2],
                ),
                "e": 1,
            },
            [],
        )
        td = tree_map(lambda x: x + 1, td)
        assert (td == 2).all()
        assert td.shape == torch.Size([])
        assert td["a"].shape == torch.Size([2])
        assert td["a", "b"].shape == torch.Size([2, 3])
        assert td["a", "b", "c"].shape == torch.Size([2, 3, 4])
</code></pre>
<p>This means that operations that affect the batch-size (eg, <code>TensorDict.flatten</code>) <strong>cannot</strong> be implemented using PyTree. Another issue with PyTree is that it deconstructs and reconstructs the content of the tensordict, which can cause some unwanted overhead.</p>
<h3><a name="nested-tensor-compatibility-11" class="anchor" href="#nested-tensor-compatibility-11"></a>Nested-tensor compatibility</h3>
<p>Per se, nested tensors can be stored within a tensordict without any apparent issue:</p>
<pre><code class="lang-python">nested = torch.nested.nested_tensor([torch.zeros(3), torch.ones(4)])
td = TensorDict({"nested_tensor": nested}, []) # no size works perfectly

nested = torch.nested.nested_tensor([torch.zeros(3), torch.ones(4)])
td = TensorDict({"nested_tensor": nested}, batch_size=[2]) # should work since we have a first dimension of shape [2]
print(td)
</code></pre>
<p>which prints</p>
<pre><code class="lang-auto">TensorDict(
    fields={
        nested_tensor: Tensor(shape=torch.Size([2, -1]), device=cpu, dtype=torch.float32, is_shared=False)},
    batch_size=torch.Size([2]),
    device=None,
    is_shared=False)
</code></pre>
<p>Indexing a single item works fine</p>
<pre><code class="lang-python">td[0] # gets the 0 valued tensor
</code></pre>
<p>but using other index types (eg, slices) raises an exception.</p>
<h3><a name="tensorclass-12" class="anchor" href="#tensorclass-12"></a><code>@tensorclass</code></h3>
<p>Users may prefer a more strongly-typed class. This can come in handy when handling datasets, as predicting what fields are present in the data structure is sometimes key to write a transparent codebase.<br>
To this aim, TensorDict comes with a specialised <code>@dataclass</code> decorator, <code>@tensorclass</code>.<br>
<code>@tensorclass</code> works exactly like <code>@dataclass</code> except from the fact that a batch-size must be passed to it during construction. Unlike <code>TensorDict</code>, a tensorclass can have dedicated methods, and it supports non-tensor data:</p>
<pre><code class="lang-python">@tensorclass
class MyData:
    images: torch.Tensor
    labels: torch.Tensor
    non_tensor: Any
    path_to_data: str
    def __post_init__(self):
        if self.path_to_data:
            self.memmap_(self.path_to_data)
    def get_data_with_label(self, label) -&gt; MyData:
        return self[self.label == label]

images = torch.randint(255, (42, 3, 64, 64))
labels = torch.randint(100, (42, 3, 64, 64))

# creates a memory-mapped dataset
data = MyData(images, labels, batch_size=[42], non_tensor=None, path_to_data="/tmp")
</code></pre>
<p>When indexing a tensorclass instance with non-tensor data, the resulting non-tensor data will be identical to those in the parent object.</p>
<p>A great thanks to <span class="mention">@apbard</span> and <span class="mention">@tcbegley</span> for the help with this!</p>
<h3><a name="printing-data-content-13" class="anchor" href="#printing-data-content-13"></a>Printing data content</h3>
<p>A minor yet useful feature is simply to see what a data structure looks like. Unlike the print of a <code>torch.Tensor</code>, a TensorDict representation will display only the tensor metadata such as shape, device and shared memory status.<br>
When looking at a dataset, this can help to get a quick understanding of the content of it. For parameter batches, this representation is also more handy than printing a <code>state_dict</code> which is something hardly anyone would do in her right mind.</p>
<h3><a name="miscellaneous-14" class="anchor" href="#miscellaneous-14"></a>Miscellaneous</h3>
<p>TensorDict supports a bunch of other features:</p>
<ul>
<li>locking: a tensordict can be locked. This will ensure that any <code>set</code> operation that does not modify a tensor in-place is prohibited. There are two ways to (un)lock a tensordict:<pre><code class="lang-python">data = data.lock_()
with data.unlock_():
    data.set("key", val)
</code></pre>
</li>
</ul>
<p>and conversely. Using <code>lock_()</code> as a decorator comes in handy when one knows that the lock should be temporarily escaped.</p>
<ul>
<li>caching results: in some cases, we know that the result of an operation will not change when called twice (for instance <code>flatten_keys</code> on a locked tensordict). In this case, the result is cached. All cached operations are very cheap in terms of memory requirements.</li>
</ul>
<h2><a name="utilisation-15" class="anchor" href="#utilisation-15"></a>Utilisation</h2>
<h3><a name="data-representation-and-manipulation-16" class="anchor" href="#data-representation-and-manipulation-16"></a>Data representation and manipulation</h3>
<p>TensorDict is ideal to represent a dataset with fast indexing (provided that the data can be represented contiguously). Any sampling from a dataset boils down to a call to <code>__getitems__</code>:</p>
<pre><code class="lang-python"># dummy training loop
for data in dataset:
    data = data.to(device, non_blocking=True)
    model(data) # provided that the model reads a tensordict, see tensordict TensorDictModule on tensordict lib for an example
    loss = loss_fn(data) 
    loss.backward()
    optim.step()
    optim.zero_grad()
</code></pre>
<p>The point of this example is that we can abstract away the content of the data and focus on the training loop itself. For instance, a training loop for image segmentation or classification wouldn’t look very different in this context.</p>
<p>It could be argued that TensorDict obfuscates the inner mechanisms of the training algorithm but we think it is the opposite, it focalises it on the relevant part (the model construction). On top of this, a print of the data during code execution is much more transparent than the same thing in a generic PyTorch script.</p>
<h3><a name="dataloading-17" class="anchor" href="#dataloading-17"></a>Dataloading</h3>
<p>PyTorch dataloaders handle sampling multiple items from a dataset by either (1) spawning multiple parallel processes and executing the indexing independently using <code>__getitem__</code> or (2) calling <code>__getitems__</code> directly.<br>
This makes <code>TensorDict</code> compelling: no need for a <code>collate_fn</code>, and if the data is contiguous, sampling is considerably faster than with mp (see figure above).</p>
<h2><a name="data-transforms-and-preproc-18" class="anchor" href="#data-transforms-and-preproc-18"></a>Data transforms and preproc</h2>
<p>The <code>TensorDict.map</code> method makes TensorDict a complelling tool for preprocessing.</p>
<p>Similarly, to get a sense of what data transform looks like with tensordict, one can have a look at <a href="https://github.com/pytorch/rl/tree/main/torchrl/envs/transforms" rel="noopener nofollow ugc">torchrl’s transforms</a> which all have a pretty simple signature: <code>transform(data)</code>, where <code>data</code> is a tensordict. With this, it is easy to imagine what a random crop that acts on an image and a mask would look like. In RL, we haven’t found (so far!) any use case where transforms composed over a bunch of tensors could not be solved with <code>TensorDict</code>. Recall that this comes with the rest of the services (eg, easy casting to device, good representation etc) which makes this feature much easier to blend in the code based than a regular dictionary.</p>
<h3><a name="distributed-features-19" class="anchor" href="#distributed-features-19"></a>Distributed features</h3>
<p>TensorDict has a bunch of torch.distributed capabilities:</p>
<ul>
<li>point-to-point communication is treated as whole, reducing any query to a single call (even for highly nested structures like parameters from a model). <code>TensorDict.gather</code>, <code>TensorDict.isend</code>, <code>TensorDict.irecv</code>, and other mirror their <code>torch.distributed</code> counterparts.</li>
<li>In <code>RPC</code> settings, <code>MemoryMappedTensor</code> provides a 3-10x speedup on node-to-node communication with a transparent communication pipeline (provided that the nodes have a shared physical storage).</li>
</ul>
<h3><a name="parameter-serialisation-20" class="anchor" href="#parameter-serialisation-20"></a>Parameter serialisation</h3>
<p>Loading part of a model with <code>torch.save</code> / <code>torch.load</code> is cumbersome. It also relies on pickle, which is unsafe. TensorDict doesn’t need any of this, and only reads and writes what is needed. The data representation on disk mirrors the data structure in the code. On top of this, <code>TensorDict</code> is compatible with <code>torchsnapshot</code> and we’re working on improving the compatibility between the two libs!</p>
<h3><a name="modules-that-use-tensordict-stored-parameters-21" class="anchor" href="#modules-that-use-tensordict-stored-parameters-21"></a>Modules that use TensorDict-stored parameters</h3>
<p><code>TensorDictParams</code> is a dedicated <code>TensorDictBase</code> subclass to host parameters and buffers.<br>
It comes in handy whenever a <code>TensorDict</code> must be stored in a module and its parameters must be accessed:</p>
<pre><code class="lang-python">params = TensorDictParams(TensorDict.from_module(module))
id_module = nn.Identity() # for the sake of simplicity
id_module.params = params
id_module.named_parameters() # contains all the params from `module` under `params` which behaves like a nn.Module
</code></pre>
<p>In some sense, <code>TensorDictParams</code> works as a <code>nn.ParameterList</code> but it supports nested and key-based features.</p>
<h2><a name="remaining-items-to-integrate-22" class="anchor" href="#remaining-items-to-integrate-22"></a>Remaining items to integrate</h2>
<ul>
<li><span class="chcklst-box fa fa-square-o fa-fw"></span> Extensive tests: WIP</li>
<li><span class="chcklst-box fa fa-square-o fa-fw"></span> doc</li>
</ul>
<h2><a name="open-questions-23" class="anchor" href="#open-questions-23"></a>Open questions</h2>
<h3><a name="torchcompile-interaction-24" class="anchor" href="#torchcompile-interaction-24"></a><code>torch.compile</code> interaction</h3>
<p>TensorDict compatibility with torch.compile is still an open question. In the library, we have dedicated classes (<code>TensorDictModule</code> and related), which go beyond the scope of this PR.<br>
IMO it would already be great to support key-based and shape-based indexing: <code>data.get("a_str")</code>, <code>data.get(("a_tuple",))</code>, <code>data.set("a_str")</code>, <code>data.get(("a_tuple",))</code>, <code>data[:3]</code> etc.<br>
This would already make it possible to build key-based models.<br>
Making one step back, I think the main question is how a TensorDict should be used within a model: if we use it like in the <code>tensordict</code> lib, a model reads data from a TensorDict instance, executes some operations, and writes all the results that are needed in the TensorDict before returning it. If the usage is more like <code>TensorDict -&gt; Tensor</code> mappings (which is way more restrictive IMO), things would change a bit.</p>
<h3><a name="torchscriptability-25" class="anchor" href="#torchscriptability-25"></a>torchscriptability</h3>
<p>A bunch of users have asked for torchscriptability. I’m not against it, it would actually help with adoption in the industry, but given the status of torch script and the amount of refactoring this would require, the opportunity cost has to be weighted carefully.</p>
<h3><a name="overhead-26" class="anchor" href="#overhead-26"></a>Overhead</h3>
<p>We made some good progress on the overhead of common ops (<code>get</code>, <code>set</code> and such), but there is always room for improvement. I would guess that <code>torch.compile</code> support for the feature would already make this problem less relevant.</p>
<h3><a name="tensor-like-interaction-27" class="anchor" href="#tensor-like-interaction-27"></a>Tensor-like interaction</h3>
<p>Tensor-like classes (broadly speaking) interaction with <code>TensorDict</code> are not very well defined. In the lib, we make sure that <code>KeyedJaggedTensors</code> from torchrec can be placed in a tensordict and key/shape-indexed accordingly. Having a clear API to register other tensor-like objects would be awesome but it isn’t clear what that would look like in practice.</p>
<h3><a name="fsdp-interaction-28" class="anchor" href="#fsdp-interaction-28"></a>FSDP interaction</h3>
<p>Intuitively, sharding a bunch of tensors with TensorDict seems “easy” to achieve (in the sense: if a common operation can be identified, it can be readily applied to a bunch of tensors). Similarly, <code>all_gather</code> and similar can be executed at every level of the model with little pain, and isolated over the relevant set of parameters every time they’re required.<br>
This is all very theoretical and I’d need to get a better understanding of the mechanisms underpinning FSDP (+ we may not want to reinvent the wheel, given the amount of work this feature requires I’m keeping my excitement level at a low level <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"> )</p>