as_tensordict_module#
- class tensordict.nn.as_tensordict_module(*, in_keys: List[NestedKey] | NestedKey, out_keys: List[NestedKey] | NestedKey)#
Bases:
objectTurns a function or a method into a tensordict module that reads
in_keysand writesout_keys.The decorated function is wrapped in a
TensorDictModule, built at the first call. Called with a tensordict, it returns the tensordict with the outputs written atout_keys. Called with tensors (seedispatch()), it returns the output tensors. On a method, one module serves all the instances of the class, and the instance is passed asselfat each call.- Keyword Arguments:
Examples
>>> import torch >>> from tensordict import TensorDict >>> from tensordict.nn import as_tensordict_module >>> @as_tensordict_module(in_keys="c", out_keys="d") ... def my_function(c): ... return c + 1 >>> my_function(TensorDict(c=0))["d"] tensor(1) >>> my_function(c=torch.zeros(2)) tensor([1., 1.])
It works on methods too:
>>> class MyClass: ... @as_tensordict_module(in_keys="c", out_keys="d") ... def my_method(self, c): ... return c + 1 >>> MyClass().my_method(TensorDict(c=0))["d"] tensor(1)