Chapter 9Second-order automatic differentiation
We review in this chapter how to perform automatic differentiation for second-order derivatives.
9.1 Hessian-vector products
We consider in this section a function . Similarly to the Jacobian, for most purposes, we do not need access to the full Hessian but rather to the Hessian-vector product (HVP) at , in a direction , as defined in Definition 2.19. The latter can be computed in four different ways, depending on how we combine the two main modes of autodiff.
9.1.1 Four possible methods
An HVP can be computed in four different ways.
Reverse on reverse: The Hessian can be seen as the transposed Jacobian of the gradient, hence the HVP can be computed as the VJP of the gradient,
Forward on reverse: Owing to its symmetry (see Proposition 2.10), the Hessian can also be seen as the Jacobian of the gradient, hence the HVP can be computed as the JVP of the gradient,
Reverse on forward: Recall that for any function , the VJP can equivalently be defined as the gradient along an output direction , that is, where we recall the shorthand , so that is a function of . In our case, we can therefore rewrite the reverse-on-reverse approach as We know that is the JVP of at along . Therefore, we can also compute the HVP as the gradient of the JVP of at along , where we use the notation to insist on the fact that it is a function of .
Forward on forward: Finally, we can use the definition of the HVP in Definition 2.19 as a vector of second partial derivatives along and each canonical direction. That is, assuming , we can compute the JVP of the JVP times:
The four different ways of computing the HVP are summarized in Table 9.1.
| Method | Computation |
|---|---|
| Reverse on reverse (VJP of gradient) | |
| Forward on reverse (JVP of gradient) | |
| Reverse on forward (gradient of JVP) | |
| Forward on forward (JVPs of JVPs) |
Table 9.1: Four different ways of computing the HVP .
9.1.2 Complexity
To get a sense of the computational and memory complexity of the four approaches, we consider a chain of functions as done in Section 8.1. To simplify our analysis, we assume for and .
The computation graph of the reverse mode is illustrated in Fig. 9.1. While would be represented by a simple chain, the computational graph of is no longer a chain: it is a DAG. This is due to the computations of , where both and depend on .
We illustrate the computation graphs of reverse-on-reverse and forward-on-reverse in Fig. 9.2 and Fig. 9.3 respectively. By applying reverse mode on reverse mode, at each fan-in operation , the reverse mode on branches out into two paths that are later merged by a sum. By applying forward mode on top of reverse mode, the flow of computations simply follows that of .

Figure 9.1: Computation graph corresponding to reverse mode autodiff for evaluating the gradient of . While is a simple chain, is a DAG.

Figure 9.2: Computation graph for computing the HVP by using reverse mode on top of reverse mode. As the computation graph of induces fan-in operations , the reverse mode applied on induces branching of the computations at each such node.

Figure 9.3: Computation graph for computing the HVP by using forward mode on top of reverse mode. The forward mode naturally follows the computations done for the gradient, except that it passes through the derivatives of the intermediate operations.
With this in mind, following a similar calculation as for Table 8.1, we obtain the following results. We assume that each is a dense linear operator, so that its application has the same cost as a matrix-vector multiplication. For the memory complexity, we consider that the inputs of each operation are saved to compute the required derivatives in the backward passes.
Reverse on reverse: time and space.
Forward on reverse: time and space.
Reverse on forward: time and space.
Forward on forward: time and space for the JVPs with .
We see that, for chains of functions, “reverse on reverse”, “forward on reverse” and “reverse on forward” all have similar time complexities up to some constant factors. Using reverse mode on top of reverse mode requires storing the information backpropagated, i.e., the (resp. the information forwarded, i.e., the in Fig. 8.1), to perform the final reverse pass. By using forward mode on top of reverse mode, this additional cost is not incurred, making it slightly less memory expensive. In addition, reverse mode on top of reverse mode induces a few additional summations due to the branching and merge operations depicted in Fig. 9.2. The same holds when using reverse on top of forward as we cannot avoid fan-in operations (this time of the form ). Unfortunately, “forward on forward” is prohibitively expensive.
To summarize, among the four approaches presented to compute HVPs, the forward-on-reverse mode is a priori the most preferable in terms of computational and memory complexities. Note, however, that computations of higher derivatives can benefit from dedicated autodiff implementations such as Taylor mode autodiff, that do not merely compose forward and reverse modes. For general functions , it is reasonable to benchmark the first three methods to determine which method is the best for the function at hand.
9.2 Gauss-Newton matrix
9.2.1 An approximation of the Hessian
The Hessian matrix of a function is often used to construct a quadratic approximation of , Unfortunately, when is nonconvex, is typically an indefinite matrix, which means that the above approximation is a nonconvex quadratic w.r.t. . For instance, if with convex, then is convex if is linear, but it is typically nonconvex if is nonlinear. The (generalized) Gauss-Newton matrix is a principled alternative to the Hessian, which is defined for .
Definition 9.1 (Gauss-Newton matrix)
Given a differentiable function and a twice differentiable function , the (generalized) Gauss-Newton matrix of the composition evaluated at a point is defined as
As studied in Section 17.2, the Gauss-Newton matrix is a key ingredient of the Gauss-Newton method. An advantage of the Gauss-Newton matrix is its positive semi-definiteness provided that is convex.
Proposition 9.1 (Positive semi-definiteness of the GN matrix)
If is convex, then is positive semi-definite for all .
This means that the approximation is a convex quadratic w.r.t. .
Using the chain rule, we find that the Hessian of decomposes into the sum of two terms (see also Proposition 9.7).
Proposition 9.2 (Approximation of the Hessian)
For and twice differentiable, we have If is linear, then the Hessian and Gauss-Newton matrices coincide,
The Gauss-Newton operator can therefore be seen as an approximation of the Hessian , with equality if is linear.
9.2.2 Gauss-Newton chain rule
A chain rule for computing the Hessian of a composition of two functions is presented in Proposition 9.7, but the formula is relatively complicated, due to the cross-terms. In contrast, a Gauss-Newton chain rule is straightforward.
Proposition 9.3 (Gauss-Newton chain rule)
9.2.3 Gauss-Newton vector product
As for the Hessian, we rarely need to materialize the full Gauss-Newton matrix in memory. Indeed, we can define the Gauss-Newton vector product (GNVP), a linear map for a direction , as where is the HVP of , a linear map from to . The GNVP can be computed using the JVP of , the HVP of and the VJP of . Instantiating the VJP requires forward pass through , from which we get both the value and the adjoint linear map . Evaluating the VJP requires backward pass through . Evaluating the JVP requires forward pass through . In total, evaluating therefore requires forward passes and backward pass through .
9.2.4 Gauss-Newton matrix factorization
In this section, we assume and . When is convex, we know that the Gauss-Newton matrix is positive semi-definite and therefore it can be factorized into for some , where is the rank of the matrix. Such a decomposition can actually be computed easily from a factorization of the Hessian of . For instance, suppose we know the eigendecomposition of the Hessian of , , where the are the eigenvectors and the are the eigenvalues (which we know are non-negative due to positive semidefiniteness). Then, the Gauss-Newton matrix can be decomposed as Stacking the vectors into a matrix , we recover the factorization . To form this decomposition, we need to perform the eigendecomposition of , which takes time. We also need calls to the VJP of at . Compared to the direct implementation in Eq. (9.1), the factorization, once computed, allows us to compute the Gauss-Newton vector product (GNVP) as . The factorization only requires memory, while the direct implementation in Eq. (9.1) requires us to maintain the intermediate computations of . The computation-memory trade-offs therefore depend on the function considered.
9.2.5 Stochastic setting
Suppose the objective function is of the form With some slight abuse of notation, we then have that the Gauss-Newton matrix associated with a pair is where . Given a distribution over pairs, the Gauss-Newton matrix associated with the averaged loss is then
9.3 Fisher information matrix
9.3.1 Definition using the score function
The Fisher information is a way to measure the amount of information in a random variable .
Definition 9.2 (Fisher information matrix)
The Fisher information matrix, or Fisher for short, associated with the negative log-likelihood of a probability distribution with parameters is the covariance of the gradients of at for distributed according to , The gradient is known as the score function.
As studied in Section 17.3, the Fisher information matrix is a key ingredient of the natural gradient descent method.
9.3.2 Link with the Hessian
Provided that the probability distribution is twice differentiable w.r.t. with integrable second derivatives, the Fisher information matrix can also be expressed as the Hessian of the negative log-likelihood (Amari, 1998; Martens, 2020).
Proposition 9.4 (Connection with the Hessian)
The Fisher information matrix of the negative log-likelihood satisfies
Remark 9.1 (Empirical Fisher)
We emphasize that in the above definitions, is sampled from the model distribution , not from the data distribution . That is, we have The latter is sometimes called ambiguously the “empirical” Fisher, though this name has generated confusion (Kunstner et al., 2019).
9.3.3 Equivalence with the Gauss-Newton matrix
So far, we discussed the Fisher information for a generic random variable . We now discuss the supervised probabilistic learning setting where and where, using the product rule of probability, we define the PDF , with the shorthand .
Proposition 9.5 (Fisher matrix in supervised setting)
Suppose where the PDF of is . In that case, the Fisher information matrix of the negative log-likelihood decomposes as: where we defined the shorthand and where we defined the negative log-likelihood loss .
When is an exponential family distribution, we can show that the Fisher information matrix and the Gauss-Newton matrix are equivalent.
Proposition 9.6 (Equivalence between Fisher and Gauss-Newton)
If is an exponential family distribution, then where .
Proof
From Proposition 3.3, if is an exponential family distribution, is actually independent of . Using Bartlett’s second identity Eq. (12.3), we then obtain where we used to indicate that the result holds for all . Plugging the result back in the Fisher information matrix concludes the proof. ◻
9.4 Inverse-Hessian vector product
9.4.1 Definition as a linear map
We will see in Section 17.1 that Newton’s method uses iterations as The inverse is well-defined if for example is strictly convex. Otherwise, some additional regularization can be added. Newton’s method therefore requires access to inverse-Hessian vector products (IHVPs), as defined below.
Definition 9.3 (Inverse-Hessian vector product)
For a twice differentiable function , we define the inverse-Hessian Vector Product (IHVP) of at as the linear map provided that it exists. In other words, it is the linear map which to associates such that .
9.4.2 Implementation with matrix-free linear solvers
Numerous direct methods exist to compute the inverse of a matrix, such as the Cholesky decomposition, QR decomposition and Gaussian elimination. However, these algorithms require accessing elementary entries of the matrix, while an autodiff framework gives access to the Hessian through HVPs. Fortunately, there exist so-called matrix-free algorithms, that can solve a linear system of equations by only accessing the linear map for any . Among such algorithms, we have the conjugate gradient (CG) method, that applies for positive-definite, i.e., such that for all , or the generalized minimal residual (GMRES) method, that applies for any invertible . A longer list of solvers can be found in public software such as SciPy (Virtanen et al., 2020). The IHVP of a strictly convex function (ensuring that the Hessian is positive definite) can therefore be computed by instantiating CG on the HVP, Positive-definiteness of the Hessian is indeed guaranteed for strictly convex functions for example, while for generic nonconvex functions, such a property may be verified around a minimizer but not in general. The conjugate gradient method is recalled in Algorithm 9.1 in its simplest form. In theory, the exact solution of the linear system is found after at most iterations of CG, though in practice numerical errors may prevent one from getting an exact solution.
Algorithm 9.1: Conjugate gradient method
Inputs: linear map , target , initialization (default ), number of iterations (default ), target accuracy (default machine precision)
for do
if then break
Output: , such that
9.4.3 Complexity
For a given matrix , solving can be done with decomposition methods (LU, QR, Cholesky) in time. For matrix-free methods such as CG or GMRES, the cost per iteration is . Since they theoretically solve the linear system in iterations, the cost to obtain an exact solution is theoretically the same, .
However, CG or GMRES differ from decomposition methods in that they are iterative methods, meaning that, at each iteration, they get closer to a solution. Unlike decomposition methods, this means that we can stop them before an exact solution is found. In practice, the number of iterations required to find a good approximate solution depends on the matrix. Well conditioned matrices require only few iterations. Badly conditioned matrices lead to some numerical instabilities for CG, so that more than iterations may be needed to get a good solution. In contrast, decomposition methods proceed in two steps: first they build a decomposition of at a cost of , and second they solve a linear system at a cost of , by leveraging the structure. LU and QR decompositions are known to be generally more stable and are therefore often preferred in practice, when we can access entries of at no cost.
If we do not have access to the Hessian , but only to its HVP, accessing entries of comes at a prohibitive cost. Indeed, entries of can still be recovered from HVPs, since , but accessing each row or column of costs one HVP (matrix-vector product). To access the information necessary to use a decomposition method, we therefore need calls to HVPs before being able to actually compute the solution. For the same number of calls, CG or GMRES will already have found an approximate solution. In addition, a CG method does not require storing the matrix in memory.
9.5 Second-order backpropagation
9.5.1 Second-order Jacobian chain rule
The essential ingredient to develop forward-mode and reverse-mode autodiff hinged upon the chain rule for composed functions, . For second derivatives, a similar rule can be obtained. To do so, we slightly abuse notation and denote where , , , and where we recall the shorthand notation . Moreover, we view the above quantity as a linear map. Strictly speaking, the superscript is not a linear adjoint anymore, since is no longer linear but bilinear. However, this superscript plays the same role as the VJP, since it takes an output vector and returns the input derivatives that correspond to infinitesimal variations along that output vector.
Proposition 9.7 (Hessian chain rule)
For two twice differentiable functions and , the second directional derivative of the composition is a bilinear map from to along input directions of the form The Hessian of the composition along an output direction is, seen as a linear map, For the composition of with a scalar-valued function , we have in matrix form
Note that, while the Hessian is usually defined for scalar-valued functions , the above definition is for a generalized notion of Hessian that works for any function .
The Hessian backpropagation rule in Eq. (9.2) reveals two terms. The first one simply computes the Hessian of the intermediate function along the output direction normally backpropagated by a VJP. The second term shows how intermediate first-order variations influence second-order derivatives of the output.
Example 9.1 (Composition with an elementwise nonlinear function)
Consider the element-wise application of a twice differentiable scalar-valued function followed by some twice differentiable function . Note that . Hence, the Hessian of the composition reads where and .
Example 9.2 (Hessian of the composition with a linear function)
Consider a linear function , for , composed with some twice differentiable function . From Proposition 9.7, we get, in terms of linear maps, As already noted in Section 2.3, we have that and . Hence, the Hessian seen as a linear map reads where .
9.5.2 Computation chains
For a simple computation chain as in Section 8.1, the formula derived in Proposition 9.7 suffices to develop an algorithm that backpropagates the Hessian, as shown in Algorithm 9.2. Compared to Algorithm 8.2, we simply backpropagate both the vectors and the matrices using intermediate first and second derivatives.
Algorithm 9.2: Hessian backprop for computation chains
Functions: with ,
Inputs: input
Initialize and store ▷ Forward pass
for do
Compute and store
Initialize ▷ Backward pass
for do
Compute
Compute
Release from memory
Outputs: , ,
9.5.3 Fan-in and fan-out
For generic computation graphs (see Section 8.3), we saw that multi-input functions (fan-in) were crucial. For Hessian backpropagation in computation graphs, we therefore need to develop a similar formula.
Proposition 9.8 (Hessian chain rule for fan-in)
Consider twice differentiable functions and with and . The Hessian of for along an output direction is given by
The gradient backpropagation expression for fan-in is simple because the functions are not linked by any path. In contrast, the Hessian backpropagation involves cross-product terms
for . The nodes associated with the computations cannot be treated independently anymore.
On the other hand, developing a backpropagation rule for fan-out does not pose any issue, since each output function can be treated independently.
Proposition 9.9 (Hessian chain rule for fan-out)
Consider twice differentiable functions and with and . The Hessian of for along a direction is given by
9.6 Block diagonal approximations
Rather than computing the whole Hessian or Gauss-Newton matrices, we can consider computing block-diagonal or diagonal approximations, which are easier to invert. The approximation rules we present in this section build upon the Hessian chain rule studied in Section 9.5.
9.6.1 Feedforward networks
Recall the definition of a feedforward network: where . Rather than computing the entire Hessian of w.r.t. , we can compute the Hessians w.r.t. each set of parameters . For the case of computation chains, the Hessian backpropagation recursion we used in Algorithm 9.2 was Extending this recursion to the feedforward network case, we obtain, starting from and , where we used to indicate that these blocks are not used. The Hessians w.r.t. each set of parameters are then The validity of this result stems from the fact that we can view the Hessian w.r.t. as computing the Hessian w.r.t. of where , for . As the computations of the block-wise Hessians share most of the computations, they can be evaluated in a single backward pass just as the gradients.
Example 9.3 (Block-wise computation of the Gauss-Newton matrix)
Our blockwise backpropagation scheme can readily be adapted for the Gauss-Newton matrix as starting from . The outputs give a block-wise approximation of the Gauss-Newton matrix.
Now, consider a simple multilayer perceptron such that Using Example 9.2 and Example 9.1 adapted to the Gauss-Newton matrix, we can compute the block-wise decomposition of the Gauss-Newton matrix as, for , starting from . The outputs correspond to the block-wise elements of the Gauss-Newton matrix of for the vectorized weights . Similar computations were done in KFRA (Botev et al., 2017) and BackPack (Dangel et al., 2019).
9.6.2 Computation graphs
For generic computation graphs, consider a function defined by, denoting , such that , and is following a topological ordering of the graph (see Section 8.3). We can consider the following backpropagation scheme, for and starting from and . Recall that for multiple inputs, the chain rule presented in Proposition 9.8 involves the cross-derivatives. For this reason the backpropagation scheme in Eq. (9.3) only computes an approximation. For example, one can verify that using Eq. (9.3) to compute the Hessian of does not provide an exact expression for the Hessian of . This scheme is easy to implement and may provide a relevant proxy for the Hessian.
9.7 Diagonal approximations
Similarly to the idea of designing a backpropagation scheme that approximates blocks of the Hessian, we can design a backpropagation scheme that approximates the diagonal of the Hessian. The approach was originally proposed by Becker and Le Cun (1988) for feedforward networks, but our exposition, new to our knowledge, has the benefit that it naturally extends to computational graphs, as we shall see.
9.7.1 Computation chains
The idea stems from modifying the Hessian backpropagation rule in Proposition 9.7 to only keep the diagonal of the Hessian. Formally, given a matrix , we denote by the vector of diagonal entries of , and for a vector , we denote the diagonal matrix with entries . For the backpropagation of the Hessian of , we see from Algorithm 9.2 that can be expressed in terms of as Unfortunately, that recursion needs access to the whole Hessian , and would therefore be too expensive. A natural idea is to modify the recursion to approximate by backpropagating vectors: The diagonal matrix serves as a surrogate for . Each iteration of this recursion can be computed in linear time in the output dimension since To initialize the recursion, we can set . As an alternative, as proposed by Elsayed and Mahmood (2022), if has a simple form, we can use instead of at the first iteration. This is the case for instance if is a cross-entropy loss. The recursion is repeated until we obtain the approximate diagonal Hessian . The gradients , needed to compute , are computed along the way and the algorithm can therefore also return .
9.7.2 Computation graphs
Although this diagonal approximation was originally derived for feedforward networks by Becker and Le Cun (1988), it is straightforward to generalize it to computation graphs. Namely, for a function decomposed along a computation graph, we can backpropagate a diagonal approximation in reverse topological order as for , starting from and or . To implement such an algorithm, each elementary function in the computational graph needs to be augmented with an oracle that computes the Hessian diagonal approximation of the current function, given the previous ones. An example with MLPs is presented in Example 9.4.
Example 9.4 (Hessian diagonal approximation for MLPs)
Consider a multilayer perceptron starting from . Here is the element-wise activation function (potentially the identity) and encapsulates the weight matrices . We consider the derivatives w.r.t. the flattened matrices, so that gradients and diagonal approximations w.r.t. these flattened quantities are vectors. The backpropagation scheme (9.5) then reduces to, denoting , starting from and, e.g., . The algorithm returns as the gradients of w.r.t. , with , and as the diagonal approximations of the Hessian w.r.t. .
9.8 Randomized estimators
In this section, we describe randomized estimators of the diagonal of the Hessian or Gauss-Newton matrices.
9.8.1 Girard-Hutchinson estimator
We begin with a generic estimator, originally proposed for trace estimation by Girard (1989) and extended by Hutchinson (1989). Let be an arbitrary square matrix, whose matrix-vector product (matvec) is available. Suppose is an isotropic random vector, i.e., such that . For example, two common choices are the Rademacher distribution and the standard normal distribution . Then, we have Applications include generalized cross-validation, computing the Kullback-Leibler divergence between two Gaussians, and computing the derivatives of the log-determinant.
The approach can be extended (Baston and Nakatsukasa, 2022; Bekas et al., 2007; Hallman et al., 2023) to obtain an estimator of the diagonal of , where denotes the Hadamard product (element-wise multiplication). This suggests that we can use the Monte-Carlo method to estimate the diagonal of , with equality as , since the estimator is unbiased. Since, as reviewed in Section 9.1 and Section 9.2, we know how to multiply efficiently with the Hessian and the Gauss-Newton matrices, we can apply the technique with these matrices. The variance is determined by the number of samples drawn and therefore by the number of matvecs performed. More elaborate approaches have been proposed to further reduce the variance (Epperly et al., 2023; Meyer et al., 2021).
9.8.2 Bartlett estimator for the factorization
Suppose the objective function is of the form where is the negative log-likelihood of an exponential family distribution, and , for some network . We saw from the equivalence between the Fisher and Gauss-Newton matrices in Proposition 9.6 (which follows from the Bartlett identity) that where indicates that the result holds for any value of the second argument. This suggests a Monte-Carlo scheme where and . In words, we can approximate the Gauss-Newton matrix with gradient computations. This factorization can also be used to approximate the GNVP in Eq. (9.1).
9.8.3 Bartlett estimator for the diagonal
Following a similar approach, we obtain where indicates the element-wise (Hadamard) product. Using a Monte-Carlo scheme, sampling from , we therefore obtain with equality when all labels in the support of have been sampled. That estimator, used for instance in (Wei et al., 2020, Appendix C.1.), requires access to individual gradients evaluated at the sampled labels. Another possible estimator of the diagonal is given by Letting , this follows from where we used that since and are independent variables for and have zero mean, from Bartlett’s first identity Eq. (12.2). We can then use the Monte-Carlo method to obtain with equality when all labels in the support of have been sampled. This estimator can be more convenient to implement, since it only needs access to the gradient of the averaged losses. However, it may suffer from higher variance. A special case of this estimator is used by Liu et al. (2023), where they draw only one for each .
9.9 Summary
By using a Hessian chain rule, we can develop a “Hessian backpropagation”. While it is reasonably simple for computation chains, it becomes computationally prohibitive for computation graphs, due to the cross-product terms occurring with fan-in.
A better approach is to use Hessian-vector products (HVPs). We saw that there are four possible methods to compute HVPs, but the forward-on-reverse method is a priori the most efficient. Similarly to computing gradients, computing HVPs is only a constant times more expensive than evaluating the function itself.
The Gauss-Newton matrix associated with the composition can be seen as an approximation of the Hessian. It is a positive semidefinite matrix if is convex, and can be used to build a principled quadratic approximation of a function. It is equivalent to the Fisher information matrix in the case of exponential families. Gauss-Newton-vector products can be computed efficiently, like HVPs.
We also described other approximations, such as (block) diagonal approximations, and randomized estimators.