PyTorch torch.vmap function
PyTorch torch reference manual
torch.vmap A function in PyTorch for vectorized mapping. It takes a function as input and returns a new function that automatically operates on batches of tensors, similar to vmap in JAX.
Function definition
torch.vmap(func, in_dims, out_dims, randomness)
Parameter Description
func: Function to vectorizein_dims: Batch dimension of the input tensors (optional)out_dims: Batch dimension of the output tensors (optional)randomness: Randomness behavior, one of "error", "different", "same"
Usage examples
Example
import
torch
Define a simple function
def
simple_func
(
x
)
:
return
x *
2
1
Vectorize a function with vmap
vectorized_func
=
torch.
vmap
(
simple_func
)
Batched input (batch dimension 0)
batch_input
=
torch.
randn
(
4
,
3
)
Apply the vectorized function
output
=
vectorized_func
(
batch_input
)
(
"Input shape:"
,
batch_input.
shape
)
(
"Output shape:"
,
output.
shape
)
(
"Output:"
)
(
output
)
The output is:
输入形状: torch.Size([4, 3])
输出形状: torch.Size([4, 3])
输出:
tensor([[ 0.2345, 1.5678, -0.3456],
[ 2.1234, -1.2345, 0.5678],
[-0.8765, 1.2345, 2.3456],
[ 1.5678, 0.1234, -1.2345]])