Jacobians, Hessians, hvp, vhp, and more: composing function transforms
intermediate/jacobians_hessians
Run in Google Colab
Colab
Download Notebook
Notebook
View on GitHub
GitHub
Computing jacobians or hessians are useful in a number of non-traditional
deep learning models. It is difficult (or annoying) to compute these quantities
efficiently using PyTorch’s regular autodiff APIs
(Tensor.backward(), torch.autograd.grad). PyTorch’s
JAX-inspired
provides ways of computing various higher-order autodiff quantities
efficiently.
Let’s think of predict as a function that maps the input x from RD→RD.
PyTorch Autograd computes vector-Jacobian products. In order to compute the full
Jacobian of this RD→RD function, we would have to compute it row-by-row
by using a different unit vector each time.
Instead of computing the jacobian row-by-row, we can use PyTorch’s
torch.vmap function transform to get rid of the for-loop and vectorize the
computation. We can’t directly apply vmap to torch.autograd.grad;
instead, PyTorch provides a torch.func.vjp transform that composes with
torch.vmap:
In a later tutorial a composition of reverse-mode AD and vmap will give us
per-sample-gradients.
In this tutorial, composing reverse-mode AD and vmap gives us Jacobian
computation!
Various compositions of vmap and autodiff transforms can give us different
interesting quantities.
PyTorch provides torch.func.jacrev as a convenience function that performs
the vmap-vjp composition to compute jacobians. jacrev accepts an argnums
argument that says which argument we would like to compute Jacobians with
respect to.
Let’s compare the performance of the two ways to compute the jacobian.
The function transform version is much faster (and becomes even faster the
more outputs there are).
In general, we expect that vectorization via vmap can help eliminate overhead
and give better utilization of your hardware.
vmap does this magic by pushing the outer loop down into the function’s
primitive operations in order to obtain better performance.
Let’s make a quick function to evaluate performance and deal with
microseconds and milliseconds measurements:
defget_perf(first,first_descriptor,second,second_descriptor):"""takes torch.benchmark objects and compares delta of second vs first."""faster=second.times[0]slower=first.times[0]gain=(slower-faster)
Performance delta: 71.7562 percent improvement with vmap
Furthermore, it’s pretty easy to flip the problem around and say we want to
compute Jacobians of the parameters to our model (weight, bias) instead of the input
Reverse-mode Jacobian (jacrev) vs forward-mode Jacobian (jacfwd)
We offer two APIs to compute jacobians: jacrev and jacfwd:
jacrev uses reverse-mode AD. As you saw above it is a composition of our
vjp and vmap transforms.
jacfwd uses forward-mode AD. It is implemented as a composition of our
jvp and vmap transforms.
jacfwd and jacrev can be substituted for each other but they have different
performance characteristics.
As a general rule of thumb, if you’re computing the jacobian of an RN→RM
function, and there are many more outputs than inputs (for example, M>N) then
jacfwd is preferred, otherwise use . There are exceptions to this rule,
but a non-rigorous argument for this follows:
In reverse-mode AD, we are computing the jacobian row-by-row, while in
forward-mode AD (which computes Jacobian-vector products), we are computing
it column-by-column. The Jacobian matrix has M rows and N columns, so if it
is taller or wider one way we may prefer the method that deals with fewer
rows or columns.
torch.Size([2048,32])/usr/local/lib/python3.12/dist-packages/torch/jit/_script.py:1491:FutureWarning: `torch.jit.script` is deprecated.Please switch to `torch.compile` or `torch.export`.
warnings.warn(
jacfwd time:<torch.utils.benchmark.utils.common. at
jacfwd time:<torch.utils.benchmark.utils.common.Measurementobject at 0x7f0b05c07ce0>jacfwd(predict, argnums=2)(weight, bias, x)4.12 ms
1 measurement,500 runs ,1 thread
jacrev time:<torch.utils.benchmark.utils.common.Measurementobject at 0x7f0b0a7a25d0>jacrev(predict, argnums=2)(weight bias x
Performance delta: 861.7510 percent improvement with jacfwd
Hessian computation with functorch.hessian
We offer a convenience API to compute hessians: torch.func.hessiani.
Hessians are the jacobian of the jacobian (or the partial derivative of
the partial derivative, aka second order).
This suggests that one can just compose functorch jacobian transforms to
compute the Hessian.
Indeed, under the hood, hessian(f) is simply jacfwd(jacrev(f)).
Note: to boost performance: depending on your model, you may also want to
use jacfwd(jacfwd(f)) or jacrev(jacrev(f)) instead to compute hessians
leveraging the rule of thumb above regarding wider vs taller matrices.
In the above examples we’ve been operating with a single feature vector.
In some cases you might want to take the Jacobian of a batch of outputs
with respect to a batch of inputs. That is, given a batch of inputs of
shape (B,N) and a function that goes from RN→RM, we would like
a Jacobian of shape (B,M,N).
If you have a function that goes from (B, N) -> (B, M) instead and are
certain that each input produces an independent output, then it’s also
sometimes possible to do this without using vmap by summing the outputs
and then computing the Jacobian of that function:
If you instead have a function that goes from RN→RM but inputs that
are batched, you compose vmap with jacrev to compute batched jacobians:
Finally, batch hessians can be computed similarly. It’s easiest to think
about them by using vmap to batch over hessian computation, but in some
cases the sum trick also works.
The naive way to compute a Hessian-vector product (hvp) is to materialize
the full Hessian and perform a dot-product with a vector. We can do better:
it turns out we don’t need to materialize the full Hessian to do this. We’ll
go through two (of many) different strategies to compute Hessian-vector products:
- composing reverse-mode AD with reverse-mode AD
- composing reverse-mode AD with forward-mode AD
Composing reverse-mode AD with forward-mode AD (as opposed to reverse-mode
with reverse-mode) is generally the more memory efficient way to compute a
hvp because forward-mode AD doesn’t need to construct an Autograd graph and
save intermediates for backward: