TensorClassModuleBase#
- class tensordict.nn.TensorClassModuleBase(*args: Any, **kwargs: Any)#
Bases:
Generic[InputClass,OutputClass],ABC,ModuleBase class of the modules that take and return a tensorclass.
Subclass
TensorClassModuleBase[InputClass, OutputClass], where each type is aTensorClasssubclass ortorch.Tensor, and implementforward(). A type checker then knows the type of the input and output, and can report a wrong field name. The class reads both types from the subscript: a subclass without it has noinput_typeandoutput_type, and itsas_td_module()raises aValueError.When both types are tensorclasses,
as_td_module()returns a module that takes and returns a tensordict, for example to put the module in aTensorDictSequential. See TensorClass: a dataclass of tensors.- Variables:
Examples
>>> from tensordict.tensorclass import TensorClass >>> from tensordict.nn import TensorClassModuleBase >>> import torch >>> >>> class InputTC(TensorClass): ... a: torch.Tensor ... b: torch.Tensor ... >>> class OutputTC(TensorClass): ... result: torch.Tensor ... >>> class AddModule(TensorClassModuleBase[InputTC, OutputTC]): ... def forward(self, x: InputTC) -> OutputTC: ... return OutputTC( ... result=x.a + x.b, ... batch_size=x.batch_size ... ) ... >>> module = AddModule() >>> input_tc = InputTC(a=torch.tensor([1.0]), b=torch.tensor([2.0]), batch_size=[1]) >>> module(input_tc).result tensor([3.])
- as_td_module() TensorClassModuleWrapper#
Returns a
TensorClassModuleWrapperof the module, which takes and returns a tensordict.The wrapper is a
TensorDictModuleBase. Itsin_keysandout_keysare the fields of the input and output classes. It returns a new TensorDict with only the output fields (seeTensorClassModuleWrapper).- Raises:
ValueError – if
input_typeoroutput_typeis not a tensorclass, or if the subclass did not set each of them to a class with the subscript.
Examples
>>> from tensordict import TensorDict >>> from tensordict.tensorclass import TensorClass >>> from tensordict.nn import TensorClassModuleBase >>> import torch >>> >>> class InputTC(TensorClass): ... x: torch.Tensor ... >>> class OutputTC(TensorClass): ... y: torch.Tensor ... >>> class MyModule(TensorClassModuleBase[InputTC, OutputTC]): ... def forward(self, input: InputTC) -> OutputTC: ... return OutputTC(y=input.x * 2, batch_size=input.batch_size) ... >>> module = MyModule() >>> td_module = module.as_td_module() >>> td = TensorDict({"x": torch.ones(3)}, batch_size=[3]) >>> td_module(td)["y"] tensor([2., 2., 2.])
- abstract forward(x: InputClass) OutputClass#
Computes the output of the module. Subclasses implement it.
- Parameters:
x (InputClass) – the input.
- Returns:
An instance of
OutputClass.