So, what is vmap?
vmap is a higher-order function. It accepts a function func and returns a new
function that maps func over some dimension of the inputs. It is highly
inspired by JAX’s vmap.
Semantically, vmap pushes the “map” into PyTorch operations called by func,
effectively vectorizing those operations.
The first use case for vmap is making it easier to handle
batch dimensions in your code. One can write a function func
that runs on examples and then lift it to a function that can
take batches of examples with vmap(func). func however
is subject to many restrictions:
it must be functional (one cannot mutate a Python data structure
inside of it), with the exception of in-place PyTorch operations.
batches of examples must be provided as Tensors. This means that
vmap doesn’t handle variable-length sequences out of the box.
One example of using vmap is to compute batched dot products. PyTorch
doesn’t provide a batched torch.dot API; instead of unsuccessfully
rummaging through docs, use vmap to construct a new function:
vmap can be helpful in hiding batch dimensions, leading to a simpler
model authoring experience.
vmap can also help vectorize computations that were previously difficult
or impossible to batch. This bring us to our second use case: batched
gradient computation.
The PyTorch autograd engine computes vjps (vector-Jacobian products).
Using vmap, we can compute (batched vector) - jacobian products.
One example of this is computing a full Jacobian matrix (this can also be
applied to computing a full Hessian matrix).
Computing a full Jacobian matrix for some function f: R^N -> R^N usually
requires N calls to autograd.grad, one per Jacobian row.
The third main use case for vmap is computing per-sample-gradients.
This is something that the vmap prototype cannot handle performantly
right now. We’re not sure what the API for computing per-sample-gradients
should be, but if you have ideas, please comment in
pytorch/pytorch#7786.
Total running time of the script: (0 minutes 0.002 seconds)