from_modules#
- tensordict.from_modules(*modules, as_module: bool = False, lock: bool = True, use_state_dict: bool = False, lazy_stack: bool = False, expand_identical: bool = False)#
Stacks the parameters and buffers of several modules in one tensordict.
The result has one batch dimension, with one element per module. Use it to run an ensemble of modules that have the same structure with
torch.vmap()andto_module(). Same astensordict.TensorDict.from_modules(): see that page for the difference between a dense and a lazy result, and for a full ensemble example.- Parameters:
*modules (Module) – the modules to get the parameters from.
- Keyword Arguments:
as_module (bool, optional) – if
True, aTensorDictParamsinstance is returned. Defaults toFalse.lock (bool, optional) – if
True, the resulting tensordict is locked. Defaults toTrue.use_state_dict (bool, optional) – if
True, the state-dict of each module is used. Defaults toFalse.lazy_stack (bool, optional) – if
True, the parameters are stacked in aLazyStackedTensorDictthat keeps the original parameters. IfFalse, they are stacked into new parameters. Exclusive withas_module. Defaults toFalse.expand_identical (bool, optional) – if
True, a parameter that is the same object in every module is expanded instead of stacked. Ignored whenlazy_stack=True. Defaults toFalse.
- Returns:
A
TensorDictwith batch size[len(modules)], aLazyStackedTensorDictiflazy_stack=True, or aTensorDictParamsifas_module=True.
Examples
>>> import torch >>> from torch import nn >>> import tensordict >>> modules = [nn.Linear(3, 4) for _ in range(2)] >>> params = tensordict.from_modules(*modules) >>> params.batch_size torch.Size([2]) >>> params["weight"].shape torch.Size([2, 4, 3])