functional_vmap#
- tensordict.nn.functional_vmap(module: Module, *, params: TensorDictBase, args: tuple = (), kwargs: dict[str, Any] | None = None, in_dims: dict[str, int] | None = None, randomness: Literal['error', 'different', 'same'] = 'error', chunk_size: int | None = None, method: str | None = None, loop: bool = False) Any#
Calls
moduleonce per set of parameters inparamsand stacks the outputs.The batch dimensions of
paramsindex the sets, for example the parameters of several modules stacked withfrom_modules(). They are flattened into one dimension andtorch.vmap()runs over it once, so every output getsparams.batch_sizeas its leading dimensions. With an empty batch size,moduleis called once withparams.- Parameters:
module (nn.Module) – the module to call.
paramsmust have the structure offrom_module()of it.- Keyword Arguments:
params (TensorDictBase) – the stacked parameters and buffers.
args (tuple, optional) – the positional inputs of
module. Every set receives the same ones. Defaults to().kwargs (dict, optional) – the keyword inputs of
module.in_dims (dict, optional) – maps keys of
kwargsto the dimension that indexes the sets. That input needsparams.batch_sizeat this dimension, and setireceives its slicei. With several batch dimensions, the value names the first of them. The other inputs are shared.randomness (str, optional) – what a random op, such as dropout, does.
"error"will raise,"different"means the randomness for each batch will be different, and"same"gives every set the same ones. Defaults to"error".chunk_size (int, optional) – the number of sets computed at once.
method (str, optional) – the name of the method of
moduleto call instead offorward.loop (bool, optional) – if
True, calls the sets one at a time and stacks the results, for modules thattorch.vmap()cannot handle. A loop cannot detect random ops, so it does not raise underrandomness="error": each set gets its own random values, as with"different". Defaults toFalse.
- Returns:
The outputs of
module, withparams.batch_sizeas leading dimensions.- Raises:
KeyError – if a key of
in_dimsis not inkwargs.ValueError – if
in_dimsis not empty andparamshas no batch dimension, if an input named inin_dimsdoes not haveparams.batch_sizeat its dimension, or ifloop=Truewithrandomness="same".
Examples
>>> import torch >>> from torch import nn >>> from tensordict import TensorDict >>> from tensordict.nn import functional_vmap >>> nets = [nn.Linear(3, 1) for _ in range(4)] >>> params = TensorDict.from_modules(*nets) >>> x = torch.randn(10, 3) >>> functional_vmap(nets[0], params=params, args=(x,)).shape torch.Size([4, 10, 1]) >>> x_per_set = torch.randn(4, 10, 3) >>> functional_vmap( ... nets[0], ... params=params, ... kwargs={"input": x_per_set}, ... in_dims={"input": 0}, ... ).shape torch.Size([4, 10, 1])