Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.vmap function

PyTorch torch.vmap function


PyTorch torch reference manual 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


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

)

print

(

"Input shape:"

,

batch_input.

shape

)

print

(

"Output shape:"

,

output.

shape

)

print

(

"Output:"

)

print

(

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]])


PyTorch torch reference manual PyTorch torch reference manual