Title: Gradients of Functions of Large Matrices
Venue: NeurIPS 2024
Accepted: yes
Keywords: Automatic differentiation

numerical methods

linear algebra

implicit differentiation

adjoint methods

differential equations

Bayesian neural networks

Gaussian processes
Abstract: Tuning scientific and probabilistic machine learning models - for example, partial differential equations, Gaussian processes, or Bayesian neural networks - often relies on evaluating functions of matrices whose size grows with the data set or the number of parameters.
While the state-of-the-art for _evaluating_ these quantities is almost always based on Lanczos and Arnoldi iterations, the present work is the first to explain how to _differentiate_ these workhorses of numerical linear algebra efficiently.
To get there, we derive previously unknown adjoint systems for Lanczos and Arnoldi iterations, implement them in JAX, and show that the resulting code can compete with Diffrax when it comes to differentiating PDEs, GPyTorch for selecting Gaussian process models and beats standard factorisation methods for calibrating Bayesian neural networks.
All this is achieved without any problem-specific code optimisation.
Find the code at [link redacted] and install the library with *pip install [redacted]*.

Gradients of Functions of Large Matrices

Abstract

Tuning scientific and probabilistic machine learning models - for example, partial differential equations, Gaussian processes, or Bayesian neural networks often relies on evaluating functions of matrices whose size grows with the data set or the number of parameters. While the state-of-the-art for evaluating these quantities is almost always based on Lanczos and Arnoldi iterations, the present work is the first to explain how to differentiate these workhorses of numerical linear algebra efficiently. To get there, we derive previously unknown adjoint systems for Lanczos and Arnoldi iterations, implement them in JAX, and show that the resulting code can compete with Diffrax when it comes to differentiating PDEs, GPyTorch for selecting Gaussian process models and beats standard factorisation methods for calibrating Bayesian neural networks. All this is achieved without any problem-specific code optimisation. Find the code at https://github.com/pnkraemer/experiments-lanczos-adjoints and install the library with pip install matfree .

1 Introduction

Automatic differentiation has dramatically altered the development of machine learning models by allowing us to forego laborious, application-dependent gradient derivations. The essence of this automation is to evaluate Jacobian-vector and vector-Jacobian products without ever instantiating the full Jacobian matrix, whose column count would match the number of parameters of the neural network. Nowadays, everyone can build algorithms around matrices of unprecedented sizes by exploiting this matrix-free implementation. However, differentiable linear algebra for Jacobian-vector products and similar operations has remained largely unexplored to this day. We introduce a new matrix-free method for automatically differentiating functions of matrices. Our algorithm yields the exact gradients of the forward pass, all gradients are obtained with the same code, and said code runs in linear time- and memory-complexity.

For a parametrised matrix A = A ( θ ) ∈ R N × N and an analytic function f : R → R , we call f ( A ) a function of the matrix (different properties of A imply different definitions of f ( A ) ; one of them is applying f to each eigenvalue of A if A is diagonalisable; see [1]). However, we assume that A is the Jacobian of a large neural network or a matrix of similar size and never materialise f ( A ) . Instead, we only care about the values and gradients of the matrix-function-vector product

assuming that A is only accessed via differentiable matrix-vector products. Table 1 lists examples.

Evaluating Equation 1 is crucial for building large machine learning models, e.g., Bayesian neural networks: A common hyperparameter-calibration loss of a (Laplace-approximated) Bayesian neural network involves the log-determinant of the generalised Gauss-Newton matrix [13]

where D θ g is the parameter-Jacobian of the neural network g , D 2 g ρ is the Hessian of the loss function ρ with respect to g ( x i ) , and α is a to-be-tuned parameter. The matrix A ( α ) in Equation 2 has as many rows and columns as the network has parameters, which makes traditional, cubic-complexity linear algebra routines for log-determinant estimation entirely unfeasible. To compute this log-determinant, one chooses between either (i) simplifying the problem by pretending that the Hessian matrix is more structured than it actually is, e.g., diagonal [14]; or (ii) approximating log det( A ) by combining stochastic trace estimation [15]

with a Lanczos iteration A ( θ ) ≈ QHQ ⊤ [16], to reduce the log-determinant to [17, 18]

The matrix H in A ≈ QHQ ⊤ has as many rows/columns as we are willing to evaluate matrix-vector products with A ; thus, it is small enough to evaluate the matrix-logarithm log( H ) in cubic complexity.

Contributions This article explains how to differentiate not just log-determinants but any Lanczos and Arnoldi iteration so we can build loss functions for large models with such matrix-free algorithms (thereby completing the pipeline in Figure 1). This kind of functionality has been sorely missing from the toolbox of differentiable programming until now, even though the demand for functions of matrices is high in all of probabilistic and scientific machine learning [e.g. 2-12, 19-31].

2 Related work

Here, we focus on applications in machine learning and illustrate how prior work avoids differentiating matrixfree decomposition methods like the Lanczos and Arnoldi iterations. Golub and Meurant [32] discuss applications outside machine learning.

Large matrix-vector product

Small factorisation

Function of large matrix

Loss

∇

∇

∇

Parameter

θ

Optimise

θ

'Cheap' linalg

(known)

(known)

Contribution

Generative models , e.g., normalising flows [27, 33], rely on the change-of-variables formula, which involves the log-determinant of the Jacobian matrix of a neural network. Behrmann et al. [9] and Chen et al. [10] combine stochastic trace estimation with a Taylor-series expansion for the matrix logarithm. Ramesh and LeCun [34] use Chebyshev expansions instead of Taylor expansions. That said, Ubaru et al. [17] demonstrate how both methods converge more slowly than the Lanczos iteration when combined with stochastic trace estimation.

Gaussian process model selection requires values and gradients of log-probability density functions of Gaussian distributions (which involve log-determinants), where the covariance matrix A ( θ ) has as many rows and columns as there are data points [35]. Recent work [6, 7, 11, 19, 23, 36] all uses some

combination of stochastic trace estimation with the Lanczos iteration, and unanimously identifies gradients of log-determinants as (' d ' shall be an infinitesimal perturbation; see Section 4)

Another round of stochastic trace estimation then estimates d µ [6, 23, 36]. In contrast, our contribution is more fundamental: not only do we derive the exact gradients of the forward pass, but our formulation also applies to, say, matrix exponentials, whereas Equation 5 only works for log-determinants. Section 5 shows how our black-box gradients match state-of-the-art code for Equation 5 [6].

Laplace approximations and neural tangent kernels face the same problem of computing derivatives of log-determinants but with the generalised Gauss-Newton (GGN) matrix from Equation 2. In contrast to the Gaussian process literature, prior work on Laplace approximations prefers structured approximations of the GGN by considering subsets of network weights [37-39], or algebraic approximations of the GGN via diagonal, KFAC, or low-rank factors [31, 40-44]. All such approximations imply simple expressions for log-determinants, which are straightforward to differentiate automatically. Unfortunately, these approximations discard valuable information about the correlation between weights, so a linear-algebra-based approach leads to superior likelihood calibration (Section 7).

Linear differential equations , for instance ˙ y ( t ) = Ay ( t ) , y (0) = y 0 are solved by matrix exponentials, y ( t ) = exp( At ) y 0 . By this relation, matrix exponentials have frequent applications not just for the simulation of differential equations [e.g. 2, 45], but also for the construction of exponential integrators [3, 26, 29], state-space models [5, 46], and in generative modelling [4, 26, 28, 47]. There are many ways of computing matrix exponentials [48, 49], but only Al-Mohy and Higham [50] consider the problem of differentiating it and only in forward mode. In contrast, differential equations have a rich history of adjoint methods [e.g. 51, 52] with high-performance open-source libraries [53-56]. Still, the (now differentiable) Arnoldi iteration can compete with state-of-the-art solvers in JAX (Section 6).

3 Problem statement

Recall A = A ( θ ) ∈ R N × N from Section 1. The focus of this paper is on matrices that are too large to store in memory, like Jacobians of neural networks or discretised partial differential equations:

Assumption 3.1. A ( θ ) is only accessed via differentiable matrix-vector products ( θ, v ) ↦→ A ( θ ) v .

The de-facto standard for linear algebra under Assumption 3.1 are matrix-free algorithms [e.g. 57, Chapters 10 & 11], like the conjugate gradient method for solving large sparse linear systems [58]. But there is more to matrix-free linear algebra than conjugate gradient solvers:

Matrix-free implementations of matrix decompositions usually revolve around variations of the Arnoldi iteration [59], which takes an initial vector v ∈ R N and a prescribed number of iterations K ∈ N and produces a column-orthogonal Q ∈ R N × K , structured H ∈ R K × K , residual vector r ∈ R N , and length c ∈ R such that

A

(

θ

)

Q

=

Q

H

+

r

e

K

hold (Figure 2; e 1 , e K ∈ R K are the first and last unit vectors). If A is symmetric, H is tridiagonal, and the Arnoldi iteration becomes the Lanczos iteration [16]. Both iterations are popular for implementing matrix-function-vector products in a matrix-free fashion [1, 57], because the decomposition in Equation 6 implies A ≈ QHQ ⊤ , thus

The last step, Q ⊤ v = c -1 e 1 , is due to the orthogonality of Q . Since the number of matrix-vector products K rarely exceeds a few hundreds or thousands, the following Assumption 3.2 is mild:

Assumption 3.2. The map H ↦→ f ( H ) e 1 is differentiable, and Q fits into memory.

In summary, we evaluate functions of large matrices by firstly decomposing a large matrix into a product of small matrices (with Lanczos or Arnoldi) and, secondly, using conventional linear algebra to evaluate functions of small matrices. Functions of small matrices can already be differentiated efficiently [60-62]. This work contributes gradients of the Lanczos and Arnoldi iteration under Assumptions 3.1 and 3.2, and thereby makes matrix-free implementations of matrix decompositions and functions of large matrices (reverse-mode) differentiable.

Automatic differentiation, i.e. 'backpropagating through' the matrix decomposition, is far too inefficient to be a viable option (Figure 3; setup in Appendix A). Our approach via implicit differentiation or the adjoint method, respectively, leads to gradients that inherit the linear runtime and memory-complexity of the forward pass.

Limitations and future work The landscape of Lanczosand Arnoldi-style matrix decompositions is vast, and some adjacent problems cannot be solved by this single article: (i) Forward-mode derivatives would require a derivation separate from what comes next. Yet, since functions of matrices map many to few parameters (matrices to vectors), reverse-mode is superior to forward-mode anyway [66, p. 153]. (ii) We only consider real-valued matrices

0

50

100

150

200

250

0.0

0.1

0.2

0.3

0.4

0.5

0.6

Wall time (sec)

Forward pass

Adjoint

Backprop

N

=11948 rows

SuiteSparse: 'bcsstk18'

(for their relevance to machine learning), even though the decompositions generalise to complex arithmetic with applications in physics [67]. (iii) We assume Q fits into memory, which relates to combining Arnoldi/Lanczos with full reorthogonalisation [57, 68-71]. Relaxing this assumption requires gradients of partial reorthogonalisation (among other things), which we leave to future work.

4 The method: Adjoints of the Lanczos and Arnoldi iterations

Numerical algorithms are rarely differentiated automatically, and usually, some form of what is known as 'implicit differentiation' [66, 72] applies. The same is true for the Lanczos and Arnoldi iterations. However, and perhaps surprisingly, we differentiate the iterations like a dynamical system using the 'adjoint method' [51, 73, 74], a variation of implicit differentiation that uses Lagrange multipliers [66], and not like a linear algebra routine [60, 61, 75]. To clarify this distinction, we briefly review implicit differentiation before the core contributions of this work in Sections 4.1 and 4.2.

Notation Let d x be an infinitesimal perturbation of some x . D is the Jacobian operator, and ⟨· , ·⟩ the Euclidean inner product between two equally-sized inputs. For a loss ρ ∈ R that depends on some x , the linearisation d ρ = D x ρ d x and the gradient identity d ρ = ⟨∇ x ρ, d x ⟩ will be important [76, 77].

Implicit differentiation Let a : θ ↦→ x be a numerical algorithm that computes some x from some θ . Assume that the input and output of a ( · ) satisfy the constraint c ( θ, a ( θ )) = 0 . For instance, if a ( · ) solves Ax = b , the constraint is c ( A,b ; x ) = Ax -b with θ := { A,b } . We can use c ( · ) in combination with the chain rule to find the derivatives of a ( · ) , ( c = 0 implies d c = 0 )

In other words, we 'linearise' the constraint c ( θ, x ) = 0 . The adjoint method [78] proceeds by 'transposing' this linearisation as follows. Let ρ be a loss that depends on y with gradient ∇ y ρ and recall the gradient identity from the 'Notation' paragraph above. Then, for all Lagrange multipliers λ with the same shape as the outputs of c ( · ) , we know that since c = 0 implies d c = 0 ,

must hold. By matching Equation 9 to d ρ = ⟨∇ θ ρ, d θ ⟩ (this time, regarding ρ as a function of θ , not of x ; recall the 'Notation' paragraph), we conclude that if λ solves the adjoint system

then ∇ θ ρ := ( D θ c ) ⊤ λ must be the gradient of ρ with respect to input θ . This is the adjoint method [66, Section 10.4]. In automatic differentiation frameworks like JAX [79], this gradient implements a vector-Jacobian product with the Jacobian of a ( · ) - implicitly via the Lagrange multiplier λ , without differentiating 'through' a ( · ) explicitly. In comparison to approaches that explicitly target vector-Jacobian products with implicit differentiation [like 66, Proposition 10.1], the adjoint method shines when applied to highly structured, non-vector-valued constraints, such as dynamical systems or the Lanczos and Arnoldi iterations. The reason is that the adjoint method does not change if c ( · ) becomes matrix- or function-space-valued, as long as we can define inner products and adjoint operators, whereas other approaches (like what Blondel et al. [72] use for numerical optimisers) would become increasingly laborious in these cases. In summary, to reverse-mode differentiate a

numerical algorithm with the adjoint method, we need four steps: (i) find a constraint, (ii) linearise it, (iii) introduce Lagrange multipliers, and (iv) solve the resulting adjoint system. Carrying out those four steps for the Lanczos and Arnoldi iterations is the main contribution of the paper: Section 4.1 states both adjoint systems and Section 4.2 covers a matrix-free implementation.

4.1 Adjoint system of the Arnoldi and Lanczos iterations

Let e j be the j th unit vector. Denote by ' ◦ ' the element-wise matrix product, and define the matrices

so that for example, I ≤ ◦ A extracts the lower triangular matrix of A (including the diagonal), and I ≪ ◦ A = 0 enforces Hessenberg form [57]. The following two theorems do not require Assumptions 3.1 and 3.2, which are only relevant for analysing the computational complexities.

Theorem 4.1 (Adjoint system of the Arnoldi iteration) . Let K ∈ N , v ∈ R , and A ∈ R N × N , and a loss ρ ( · ) ∈ R be given. If Q ∈ R N × K , H ∈ R K × K , r ∈ R N , and c ∈ R solve the forward constraint

and if λ ∈ R N , Λ ∈ R N × K , γ ∈ R K , Γ ∈ R K × K , and Σ ∈ R K × K satisfy the adjoint system

then the gradients of ρ with respect to A and v are

Sketch of the proof. To derive the statement, start with Equation 12 as c ( · ) . Apply the chain- and product rules liberally to get d c ( · ) . Introduce Lagrange multipliers λ , Λ , γ , Γ , and Σ like in the previous section, by adding Lagrange-multiplied constraints to

and rearrange the terms to see that Equation 13 implies Equation 14. Details are in Appendix B.

Theorem 4.2 (Adjoint system of the Lanczos iteration) . Let a symmetric A ∈ R N × N , as well as v ∈ R N , K ∈ N , and a loss ρ be known. In the following equations, set b 0 := 1 ∈ R , x 0 := 0 ∈ R n , λ K +1 := 0 , µ 0 := 0 , ν 0 := 0 to simplify the expressions. If x 1 , ..., x K +1 ∈ R N , and a 1 , ..., a k , b 1 , ..., b k ∈ R K , satisfy the forward constraint

and if λ 0 , ..., λ K ∈ R N , µ 1 , ..., µ K , ν 1 , ..., ν K ∈ R satisfy the adjoint system

where all expressions involving k hold for all k = K,..., 1 , then

are the gradients of ρ with respect to v and A .

Sketch of the proof. This theorem is proven similarly to that of Theorem 4.1, but instead of a few equations involving matrices, we have many equations involving scalars because for symmetric matrices, H must be tridiagonal [57], and we expand AQ = QH + r ( e K +1 ) ⊤ column-wise. The coefficients a k and b k are the tridiagonal elements in H . We rename q k from Arnoldi to x k for Lanczos to make it easier to distinguish the two different sets of constraints. Details: Appendix C.

4.2 Matrix-free implementation

Solving the adjoint systems To compute ∇ A ρ and ∇ v ρ , we need to solve the adjoint systems. When comparing the forward constraints to the adjoint systems, similarities emerge: for instance, the adjoint system of the Arnoldi iteration follows the same A ( ⊤ ) H -Λ H ( ⊤ ) + rest = 0 structure as the forward constraint. This structure suggests deriving a recursion for the backward pass that mirrors that of the forward pass. Appendix E contains this derivation and contrasts the resulting algorithm with that of the forward pass. The main observation is that the complexity of the adjoint passes for Lanczos and Arnoldi mirrors that of the forward passes. Gradients can be implemented purely with matrix-vector products, which is helpful because it makes our custom backward pass as matrixfree as backpropagation 'through' the forward pass would be. This matrix-free implementation in combination with the efficient recursions in Theorems 4.1 and 4.2 explains the significant performance gains of our method compared to naive backpropagation, observed in Figure 3.

Theorems 4.1 and 4.2's expressions for ∇ A ρ are not directly applicable when we only have matrixvector products with A . Fortunately, parameter-gradients emerge from matrix-gradients:

Corollary 4.3 (Parameter gradients) . Under Assumption 3.1 and the assumptions of Theorem 4.1, and if A is parametrised by some θ , the gradients of ρ with respect to θ are

which can be assembled online during the backward pass. For the Lanczos iteration, we assume the conditions of Theorem 4.2 instead of Theorem 4.1, replace Qe k and Λ e k with x k and λ k , let the sum run from k = 0 to k = K , and the rest of this statement remains true.

Sketch of the proof. The proof of this identity combines the expression(s) for ∇ A ρ from Theorems 4.1 and 4.2 with d A = D θ A d θ . The derivations are lengthy and therefore relegated to Appendix D.

Reorthogonalisation It is well known that the Lanczos and Arnoldi iterations suffer from a loss of orthogonality and that reorthogonalisation of the columns in Q is often necessary [68-71]. Reorthogonalisation does not affect the forward constraints, so the adjoint systems remain the same with and without reorthogonalisation. But adjoint systems also suffer from a loss of orthogonality: The equivalent of orthogonality for the adjoint system is the projection constraint in Equation 13b, which constrains the Lagrange multipliers Λ to a hyperplane defined by Q and other known quantities. The constraint can - and should (Table 2) - be used whenever the forward pass requires reorthogonalisation. 1 In the case studies below, we always

Table 2: Accuracy loss when differentiating the Arnoldi iteration on a Hilbert matrix in double precision ( ϕ : decompose with a full-rank Arnoldi iteration, then reconstruct the original matrix; measure ∥ ∂ϕ -I ∥ ; details in Appendix F).

use full reorthogonalisation on the forward and adjoint pass, also for the Arnoldi iteration [71, Table 7.1], even though this is slightly less common than for the Lanczos iteration.

Summary (before the case studies) The main takeaway from Sections 4.1 and 4.2 is that now, we do not only have closed-form expressions for the gradients of Arnoldi and Lanczos iterations (Theorems 4.1 and 4.2), but that we can compute them in the same complexity as the forward pass, in a numerically stable way, and evaluate parameter-gradients in linear time- and spacecomplexity (Corollary 4.3). While some of the derivations are somewhat technical, the overall

approach follows the general template for the adjoint method relatively closely. The resulting algorithm beats backpropagation 'through' the iterations by a margin in terms of speed (Figure 3) and enjoys the same stability gains from reorthogonalisation as the forward pass (Table 2). Our open-source implementation of reverse-mode differentiable Lanczos and Arnoldi iterations can be installed via ' pip install matfree '. Next, we put this code to the test on three challenging machine-learning problems centred around functions of matrices to see how it fares against state-ofthe-art differentiable implementations of exact Gaussian processes (Section 5), differential equation solvers (Section 6), and Bayesian neural networks (Section 7).

5 Case study: Exact Gaussian processes

Model selection for Gaussian processes has arguably been the strongest proponent of the Lanczos iteration and similar matrix-free algorithms in recent years [6, 7, 11, 19, 20, 23, 80], and most of these efforts have been bundled up in the GPyTorch library [6]. For example, GPyTorch defaults to choosing a Lanczos iteration over a Cholesky decomposition as soon as the dataset exceeds 800 data points. 2 Calibrating hyperparameters of Gaussian process models involves optimising logmarginal-likelihoods of the regression targets, which requires computing x ⊤ A -1 x and log det( A ) for a covariance matrix A with as many rows and columns as there are data points. Recent works [6, 7, 11, 19, 20, 23, 80] unanimously suggest to differentiate log-determinants via µ := trace (log( A )) and d µ = trace ( A -1 d A ) (Equation 5). Since we seem to be the first to take a different path, benchmarking Gaussian processes in comparison to GPyTorch is a good first testbed for our gradients.

Setup: Like GPyTorch's defaults We mimic recent suggestions for scalable Gaussian process models [7, 19]: we implement a pivoted Cholesky preconditioner [81] and combine it with conjugate gradient solvers for x ⊤ K -1 x (which can be differentiated efficiently). We estimate the log-determinant stochastically via log det( A ) = trace (log( A )) = E [ v ⊤ log( A ) v ] , and compute log( A ) v via the Lanczos iteration. While all of the above is common for 'exact' Gaussian processes [6, 7, 19] ('exact' as opposed to variational approaches, which are not relevant for this comparison), there are three key differences between our code and GPyTorch's: (i) GPyTorch is in Pytorch and uses KeOps [82] for efficient kernel-matrix-vector products. We use JAX and must build our own low-memory matrix-vector products (Appendix G). (ii) GPyTorch runs all algorithms adaptively (we specify tolerances and maximum iterations as much as possible). We use adaptive conjugate gradient solvers and fixed ranks for everything else. (iii) GPytorch differentiates the log-determinant with a tailored approximation of Equation 5 [6]; we embed our gradients of the Lanczos iteration into automatic differentiation. To keep the benchmark objective, we mimic the parameter suggestions from GPyTorch's default settings, and optimise hyperparameters of a Mat´ ern ( 3 2 ) model on UCI datasets with the Adam optimiser [83]. Appendix H lists parameters and discusses the datasets.

10 1

10 2

No. Matvecs

10

4

10

2

10 0

RMSE (relative)

Forward error

A1.

Dopri5

Tsit5

10 1

10 2

No. Matvecs

10

4

10

2

10 0

Gradient error

A2.

Dopri5

Tsit5

0

100

200

300

400

500

600

700

800

Time (sec)

10

2

10

1

Loss

Training loss

B.

Arnoldi (ours), 3000 epochs

Dopri5, 3000 epochs

Tsit5, 3000 epochs

Analysis: Trains like GPyTorch; large scale only limited by matrix-vector-product backends In this benchmark, we are looking for low reconstruction errors, fast runtimes and well-behaved loss functions. Table 3 shows that this is the case for both implementations: the reconstruction errors are essentially the same, and both methods converge well (we achieve lower training losses). This result shows that by taking a numerically exact gradient of the Lanczos iteration, and leaving everything else to automatic differentiation, matches the performance of state-of-the-art solvers. Larger datasets are only limited by the efficiency of our matrix-vector products (in comparison to KeOps); Appendix G discusses this in detail. Overall, this result strengthens the democratisation of exact Gaussian processes because it reveils a simple yet effective alternative to GPyTorch's domain-specific gradients.

6 Case study: Physics-informed machine learning with PDEs

Much of the paper thus far discusses functions of matrices in the context of log-determinants. So, in order to demonstrate performance for (i) a problem that is not a log-determinant and (ii) for a non-symmetric matrix which requires Arnoldi instead of Lanczos, we learn the coefficient field ω of

subject to Neumann boundary conditions. We discretise this equation on a 128 × 128 grid in space and transform the resulting 128 2 -dimensional second-order ordinary differential equation into a first-order differential equation, ˙ w = Aw , w (0) = w 0 , with solution operator w ( t ) = exp( At ) w 0 . The system matrix A is sparse, asymmetric, and has 32 , 768 rows and columns. We sample a true ω from a Gaussian process with a square exponential kernel and generate data by sampling 256 initial conditions and solving the equation numerically with high precision. Details are in Appendix I.

Setup: Arnoldi vs Diffrax's Runge-Kutta methods for a 250k parameter MLP We learn ω with a multi-layer perceptron (MLP) with approximately 250,000 parameters. We had similar reconstructions with fewer parameters but use 250,000 to display how gradients of the Arnoldi iteration scale to many parameters. We compare an implementation of the solution operator ( θ, w 0 ) ↦→ exp( A ( θ )) w 0 with the Arnoldi iteration to Diffrax's [54] implementation of 'Dopri5' [84, 85]

with a differentiate-then-discretise adjoint [86] as well as 'Tsit5' [87] with a discretise-then-differentiate adjoint (recommended by [53, 54]). All methods receive equal matrix-vector products per simulation.

Analysis: All methods train, but Arnoldi is more accurate for fixed matrix-vector-product budgets We evaluate the approximation errors in computing the values and gradients of a mean-squared error loss for all three solvers and then use the solvers to train the MLP. We are looking for low approximation errors for few matrix-vector products and for a good reconstruction of the truth. Figure 5 shows the results. The Arnoldi iteration has the lowest forward-pass and gradient error, but Table 4 demonstrates how all ap-

0.0

0.5

1.0

0.0

0.5

1.0

Truth

0.0

0.5

1.0

0.0

0.5

1.0

Solver:

Arnoldi

(

ours

)

0.0

0.5

1.0

0.0

0.5

1.0

Solver: Dopri5

0.0

0.5

1.0

0.0

0.5

1.0

Solver: T sit5

0.000

0.002

0.004

0.006

0.008

0.010

0.012

0.014

0.000

0.002

0.004

0.006

0.008

0.010

0.012

0.014

0.000

0.002

0.004

0.006

0.008

0.010

0.012

0.014

0.000

0.002

0.004

0.006

0.008

0.010

0.012

0.014

proaches lead to low errors on ω as well as on a test set (a held-back percentage of the training data); see also Figure 4. The adjoints of the Arnoldi iteration match the efficiency of the differentiate-thendiscretise adjoint [86], and both outperform the discretise-then-differentiate adjoint by a margin. This shows how linear-algebra solutions to matrix exponentials can compete with highly optimised differential equation solvers. We anticipate ample opportunities of using the now-differentiable Arnoldi iteration for physics-based machine learning.

7 Case study: Calibrating Bayesian neural networks

Next, we differentiate a function of a matrix on a problem that is native to machine learning: marginal likelihood optimisation of a Bayesian neural network (a high-level introduction is in Appendix J).

Setup: Laplace-approximation of a VAN pre-trained on ImageNet We consider as g θ ( x ) a 'Visual Attention Network' [88] with 4,105,800 parameters, pre-trained on ImageNet [89]. We assume p ( θ ) = N (0 , α -2 I ) , and Laplace-approximate the log-marginal likelihood of the data as

where A ( α ) is the generalised Gauss-Newton matrix (GGN) from Section 1 (recall Equation 2).

300

400

Diagonal

Lanczos

0 100 200 Epochs 0.2 0.4 0.6 0.8 1.0 Neg. Log-marg. ×10 6 We optimise α via Equation 21, implementing the log-determinant via stochastic trace estimation in combination with a Lanczos iteration (like in Section 5). Contemporary works [31, 37-43] rely on sparse approximations of the GGN (such as diagonal or KFAC approximations), so we compare our implementation to a diagonal approximation of the GGN matrix, which yields closed-form logdeterminants. The exact diagonal of the 4-million-column GGN matrix would require 4 million GGN-vector products with unit vectors, and like Deng et al. [90], we find this too expensive and resort to stochastic diagonal approximation (similar to trace estimation; all details are in Appendix J). We give both the stochastic diagonal approximation and our Lanczos-based estimator exactly 150

approx. for a Bayesian VAN. matrix-vector products to approximate Equation 21. We compare the evolution of the loss function over time and various uncertainty calibration metrics. Figure 6 demonstrates training and Table 5 shows results.

Analysis: Lanczos uses matrix-vector products better (by a margin) The results suggest how, for a fixed matrix-vector-product budget, Lanczos achieves a drastically better likelihood at a similar computational budget and already shows significant improvement with a much smaller budget. Lanczos outperforms the diagonal approximation on all metrics except ECE. The subpar performance of the diagonal approximation matches the observations of Ritter et al. [31]; see also [14]. The main takeaway from this study is that differentiable matrix-free linear algebra unlocks new techniques for Laplace approximations and allows further advances for Bayesian neural networks in general.

Acknowledgments and Disclosure of Funding

This work was supported by a research grant (42062) from VILLUM FONDEN. The work was partly funded by the Novo Nordisk Foundation through the Center for Basic Machine Learning Research in Life Science (NNF20OC0062606). This project received funding from the European Research Council (ERC) under the European Union's Horizon programme (grant agreement 101125993).

References

Nicholas J Higham. Functions of Matrices: Theory and Computation . SIAM, 2008.

Efstratios Gallopoulos and Yousef Saad. Efficient solution of parabolic equations by Krylov approximation methods. SIAM Journal on Scientific and Statistical Computing , 13(5):12361264, 1992.

Marlis Hochbruck and Alexander Ostermann. Exponential integrators. Acta Numerica , 19: 209-286, 2010.

Changyi Xiao and Ligang Liu. Generative flows with matrix exponential. In International Conference on Machine Learning , pages 10452-10461. PMLR, 2020.

Patrik Axelsson and Fredrik Gustafsson. Discrete-time solutions to the continuous-time differential Lyapunov equation with applications to Kalman filtering. IEEE Transactions on Automatic Control , 60(3):632-643, 2014.

Jacob Gardner, Geoff Pleiss, Kilian Q Weinberger, David Bindel, and Andrew G Wilson. GPyTorch: Blackbox matrix-matrix Gaussian process inference with GPU acceleration. In Advances in Neural Information Processing Systems , 2018.

Jonathan Wenger, Geoff Pleiss, Philipp Hennig, John Cunningham, and Jacob Gardner. Preconditioning for scalable Gaussian process hyperparameter optimization. In International Conference on Machine Learning . PMLR, 2022.

Alexander Immer, Tycho FA Van Der Ouderaa, Mark Van Der Wilk, Gunnar Ratsch, and Bernhard Sch¨ olkopf. Stochastic marginal likelihood gradients using neural tangent kernels. In International Conference on Machine Learning , pages 14333-14352. PMLR, 2023.

Jens Behrmann, Will Grathwohl, Ricky TQ Chen, David Duvenaud, and J¨ orn-Henrik Jacobsen. Invertible residual networks. In International Conference on Machine Learning , pages 573582. PMLR, 2019.

Ricky TQ Chen, Jens Behrmann, David K Duvenaud, and J¨ orn-Henrik Jacobsen. Residual flows for invertible generative modeling. In Advances in Neural Information Processing Systems , volume 32, 2019.

Geoff Pleiss, Jacob Gardner, Kilian Weinberger, and Andrew Gordon Wilson. Constant-time predictive distributions for Gaussian processes. In International Conference on Machine Learning , pages 4114-4123. PMLR, 2018.

Chris Finlay, J¨ orn-Henrik Jacobsen, Levon Nurbekyan, and Adam Oberman. How to train your neural ODE: the world of Jacobian and kinetic regularization. In International Conference on Machine Learning , pages 3154-3164. PMLR, 2020.

Nicol N Schraudolph. Fast curvature matrix-vector products for second-order gradient descent. Neural Computation , 14(7):1723-1738, 2002.

Erik Daxberger, Agustinus Kristiadi, Alexander Immer, Runa Eschenhagen, Matthias Bauer, and Philipp Hennig. Laplace redux - effortless Bayesian deep learning. Advances in Neural Information Processing Systems , 34:20089-20103, 2021.

Michael F Hutchinson. A stochastic estimator of the trace of the influence matrix for Laplacian smoothing splines. Communications in Statistics-Simulation and Computation , 18(3):10591076, 1989.

Cornelius Lanczos. An iteration method for the solution of the eigenvalue problem of linear differential and integral operators. 1950.

Shashanka Ubaru, Jie Chen, and Yousef Saad. Fast estimation of tr( f ( A )) via stochastic Lanczos quadrature. SIAM Journal on Matrix Analysis and Applications , 38(4):1075-1099, 2017.

Tyler Chen and Eric Hallman. Krylov-aware stochastic trace estimation. SIAM Journal on Matrix Analysis and Applications , 44(3):1218-1244, 2023.

Ke Wang, Geoff Pleiss, Jacob Gardner, Stephen Tyree, Kilian Q Weinberger, and Andrew Gordon Wilson. Exact Gaussian processes on a million data points. Advances in Neural Information Processing Systems , 32, 2019.

Kaiwen Wu, Jonathan Wenger, Haydn Jones, Geoff Pleiss, and Jacob R Gardner. Largescale Gaussian processes via alternating projection. International Conference on Artificial Intelligence and Statistics , 2024.

Josie K¨ onig, Max Pfeffer, and Martin Stoll. Efficient training of Gaussian processes with tensor product structure. Preprint on ArXiv:2312.15305 , 2023.

Alexander James Davies. Effective implementation of Gaussian process regression for machine learning . PhD thesis, University of Cambridge, 2015.

Kun Dong, David Eriksson, Hannes Nickisch, David Bindel, and Andrew G Wilson. Scalable log determinants for Gaussian process kernel learning. In Advances in Neural Information Processing Systems , 2017.

Geoff Pleiss, Martin Jankowiak, David Eriksson, Anil Damle, and Jacob Gardner. Fast matrix square roots with applications to Gaussian processes and Bayesian optimization. Advances in Neural Information Processing Systems , 33:22268-22281, 2020.

Hao Wang. The Krylov subspace methods for the computation of matrix exponentials. 2015.

Qinsheng Zhang and Yongxin Chen. Fast sampling of diffusion models with exponential integrator. International Conference on Learning Representations , 2023.

Danilo Rezende and Shakir Mohamed. Variational inference with normalizing flows. In International Conference on Machine Learning , pages 1530-1538. PMLR, 2015.

Emiel Hoogeboom, Victor Garcia Satorras, Jakub Tomczak, and Max Welling. The convolution exponential and generalized Sylvester flows. In Advances in Neural Information Processing Systems , volume 33, pages 18249-18260, 2020.

Marlis Hochbruck, Christian Lubich, and Hubert Selhofer. Exponential integrators for large systems of differential equations. SIAM Journal on Scientific Computing , 19(5):1552-1574, 1998.

Alexander Immer, Matthias Bauer, Vincent Fortuin, Gunnar R¨ atsch, and Khan Mohammad Emtiyaz. Scalable marginal likelihood estimation for model selection in deep learning. In International Conference on Machine Learning , 2021.

Hippolyt Ritter, Aleksandar Botev, and David Barber. A scalable Laplace approximation for neural networks. In International Conference on Learning Representations , volume 6, 2018.

Gene H Golub and G´ erard Meurant. Matrices, Moments and Quadrature with Applications , volume 30. Princeton University Press, 2009.

Yaron Lipman, Ricky TQ Chen, Heli Ben-Hamu, Maximilian Nickel, and Matthew Le. Flow matching for generative modeling. In International Conference on Learning Representations , 2023.

Aditya Ramesh and Yann LeCun. Backpropagation for implicit spectral densities. In Advances in Neural Information Processing Systems , 2018.

Christopher KI Williams and Carl Edward Rasmussen. Gaussian Processes for Machine Learning , volume 2. MIT Press Cambridge, MA, 2006.

Kurt Cutajar, Michael Osborne, John Cunningham, and Maurizio Filippone. Preconditioning kernel matrices. In International Conference on Machine Learning , pages 2529-2538. PMLR, 2016.

Erik Daxberger, Eric Nalisnick, James U Allingham, Javier Antor´ an, and Jos´ e Miguel Hern´ andez-Lobato. Bayesian deep learning via subnetwork inference. In International Conference on Machine Learning , pages 2510-2521. PMLR, 2021.

Agustinus Kristiadi, Matthias Hein, and Philipp Hennig. Being Bayesian, even just a bit, fixes overconfidence in ReLu networks. In International Conference on Machine Learning , pages 5436-5446. PMLR, 2020.

Jasper Snoek, Oren Rippel, Kevin Swersky, Ryan Kiros, Nadathur Satish, Narayanan Sundaram, Mostofa Patwary, Mr Prabhat, and Ryan Adams. Scalable Bayesian optimization using deep neural networks. In International Conference on Machine Learning , pages 2171-2180. PMLR, 2015.

John Denker and Yann LeCun. Transforming neural-net output levels to probability distributions. Advances in Neural Information Processing Systems , 3, 1990.

Hippolyt Ritter, Aleksandar Botev, and David Barber. Online structured Laplace approximations for overcoming catastrophic forgetting. Advances in Neural Information Processing Systems , 31, 2018.

Wesley J Maddox, Gregory Benton, and Andrew Gordon Wilson. Rethinking parameter counting in deep models: Effective dimensionality revisited. arXiv preprint arXiv:2003.02139 , 2020.

Apoorva Sharma, Navid Azizan, and Marco Pavone. Sketching curvature for efficient out-ofdistribution detection for deep neural networks. In Uncertainty in Artificial Intelligence , pages 1958-1967. PMLR, 2021.

Marco Miani, Frederik Warburg, Pablo Moreno-Mu˜ noz, Nicki Skafte Detlefsen, and Søren Hauberg. Laplacian autoencoders for learning stochastic representations. In Advances in Neural Information Processing Systems , 2022.

Marlis Hochbruck and Christian Lubich. On Krylov subspace approximations to the matrix exponential operator. SIAM Journal on Numerical Analysis , 34(5):1911-1925, 1997.

Simo S¨ arkk¨ a and Arno Solin. Applied Stochastic Differential Equations , volume 10. Cambridge University Press, 2019.

Severi Rissanen, Markus Heinonen, and Arno Solin. Generative modelling with inverse heat dissipation. In International Conference on Learning Representations , 2023.

Cleve Moler and Charles Van Loan. Nineteen dubious ways to compute the exponential of a matrix. SIAM Review , 20(4):801-836, 1978.

Cleve Moler and Charles Van Loan. Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later. SIAM Review , 45(1):3-49, 2003.

Awad H Al-Mohy and Nicholas J Higham. Computing the Fr´ echet derivative of the matrix exponential, with an application to condition number estimation. SIAM Journal on Matrix Analysis and Applications , 30(4):1639-1657, 2009.

Yang Cao, Shengtai Li, Linda Petzold, and Radu Serban. Adjoint sensitivity analysis for differential-algebraic equations: The adjoint DAE system and its numerical solution. SIAM Journal on Scientific Computing , 24(3):1076-1089, 2003.

Moritz Diehl and S´ ebastien Gros. Numerical optimal control. Optimization in Engineering Center (OPTEC) , 2011.

Christopher Rackauckas and Qing Nie. DifferentialEquations.jl-a performant and feature-rich ecosystem for solving differential equations in Julia. Journal of Open Research Software , 5(1): 15-15, 2017.

Patrick Kidger. On Neural Differential Equations . PhD thesis, University of Oxford, 2021.

Chris Rackauckas, Mike Innes, Yingbo Ma, Jesse Bettencourt, Lyndon White, and Vaibhav Dixit. DiffEqFlux.jl-a julia library for neural differential equations. arXiv preprint arXiv:1902.02376 , 2019.

Yingbo Ma, Vaibhav Dixit, Michael J Innes, Xingjian Guo, and Chris Rackauckas. A comparison of automatic differentiation and continuous sensitivity analysis for derivatives of differential equation solutions. In 2021 IEEE High Performance Extreme Computing Conference (HPEC) , pages 1-9. IEEE, 2021.

Gene H Golub and Charles F Van Loan. Matrix Computations . JHU press, 2013.

Magnus Rudolph Hestenes, Eduard Stiefel, et al. Methods of conjugate gradients for solving linear systems , volume 49. NBS Washington, DC, 1952.

Walter Edwin Arnoldi. The principle of minimized iterations in the solution of the matrix eigenvalue problem. Quarterly of Applied Mathematics , 9(1):17-29, 1951.

Matthias Seeger, Asmus Hetzel, Zhenwen Dai, Eric Meissner, and Neil D Lawrence. Autodifferentiating linear algebra. Preprint on ArXiv:1710.08717 , 2017.

Sebastian F Walter and Lutz Lehmann. Algorithmic differentiation of linear algebra functions with application in optimum experimental design (extended version). Preprint on ArXiv:1001.1654 , 2010.

Andreas Griewank and Andrea Walther. Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation . SIAM, 2008.

Scott P Kolodziej, Mohsen Aznaveh, Matthew Bullock, Jarrett David, Timothy A Davis, Matthew Henderson, Yifan Hu, and Read Sandstrom. The SuiteSparse matrix collection website interface. Journal of Open Source Software , 4(35):1244, 2019.

Timothy A Davis and Yifan Hu. The University of Florida sparse matrix collection. ACM Transactions on Mathematical Software (TOMS) , 38(1):1-25, 2011.

Iain S Duff, Roger G Grimes, and John G Lewis. Sparse matrix test problems. ACM Transactions on Mathematical Software (TOMS) , 15(1):1-14, 1989.

Mathieu Blondel and Vincent Roulet. The elements of differentiable programming. arXiv preprint arXiv:2403.14606 , 2024.

Gerrit C Groenenboom and Henk M Buck. Solving the discretized time-independent Schr¨ odinger equation with the Lanczos procedure. The Journal of Chemical Physics , 92 (7):4374-4379, 1990.

Christopher Conway Paige. The computation of eigenvalues and eigenvectors of very large sparse matrices. PhD thesis, University of London, 1971.

Christopher C Paige. Computational variants of the Lanczos method for the eigenproblem. IMA Journal of Applied Mathematics , 10(3):373-381, 1972.

Christopher C Paige. Error analysis of the Lanczos algorithm for tridiagonalizing a symmetric matrix. IMA Journal of Applied Mathematics , 18(3):341-349, 1976.

Steffen B¨ orm and Christian Mehl. Numerical methods for Eigenvalue Problems . Walter de Gruyter, 2012.

Mathieu Blondel, Quentin Berthet, Marco Cuturi, Roy Frostig, Stephan Hoyer, Felipe LlinaresL´ opez, Fabian Pedregosa, and Jean-Philippe Vert. Efficient and modular implicit differentiation. Advances in Neural Information Processing Systems , 35:5230-5242, 2022.

Michael Betancourt, Charles C Margossian, and Vianey Leos-Barajas. The discrete adjoint method: Efficient derivatives for functions of discrete sequences. Preprint on ArXiv:2002.00326 , 2020.

Brian Kha Tran and Melvin Leok. Geometric methods for adjoint systems. Journal of Nonlinear Science , 34(1):25, 2024.

Denisa AO Roberts and Lucas R Roberts. QR and LQ decomposition matrix backpropagation algorithms for square, wide, and deep-real or complex-matrices and their software implementation. Preprint on ArXiv:2009.10071 , 2020.

Thomas P Minka. Old and new matrix algebra useful for statistics. See www.stat.cmu.edu/minka/papers/matrix.html , 4, 2000.

Mike Giles. An extended collection of matrix derivative results for forward and reverse mode automatic differentiation. 2008.

Jean C´ ea. Conception optimale ou identification de formes, calcul rapide de la d´ eriv´ ee directionnelle de la fonction coˆ ut. ESAIM: Mod´ elisation math´ ematique et analyse num´ erique , 20(3):371-402, 1986.

James Bradbury, Roy Frostig, Peter Hawkins, Matthew James Johnson, Chris Leary, Dougal Maclaurin, George Necula, Adam Paszke, Jake VanderPlas, Skye Wanderman-Milne, and Qiao Zhang. JAX: composable transformations of Python+NumPy programs, 2018. URL http://github.com/google/jax .

Andrew Wilson and Hannes Nickisch. Kernel interpolation for scalable structured Gaussian processes (KISS-GP). In International Conference on Machine Learning , pages 1775-1784. PMLR, 2015.

Helmut Harbrecht, Michael Peters, and Reinhold Schneider. On the low-rank approximation by the pivoted Cholesky decomposition. Applied Numerical Mathematics , 62(4):428-440, 2012.

Benjamin Charlier, Jean Feydy, Joan Alexis Glaunes, Franc ¸ois-David Collin, and Ghislain Durif. Kernel operations on the GPU, with autodiff, without memory overflows. Journal of Machine Learning Research , 22(74):1-6, 2021.

Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. San Diega, CA, USA, 2015.

J. R. Dormand and P. J. Prince. A family of embedded Runge-Kutta formulae. J. Comp. Appl. Math , 6:19-26, 1980.

Lawrence F. Shampine. Some practical Runge-Kutta formulas. Mathematics of Computation , 46(173):135-150, 1986. doi: https://doi.org/10.2307/2008219.

Ricky TQ Chen, Yulia Rubanova, Jesse Bettencourt, and David K Duvenaud. Neural ordinary differential equations. Advances in Neural Information Processing Systems , 31, 2018.

Charalampos Tsitouras. Runge-Kutta pairs of order 5 (4) satisfying only the first column simplifying assumption. Computers & Mathematics with Applications , 62(2):770-775, 2011.

Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, and Shi-Min Hu. Visual attention network. Computational Visual Media , 9(4):733-752, 2023.

Jia Deng, Wei Dong, Richard Socher, Li-Jia Li, Kai Li, and Li Fei-Fei. ImageNet: A large-scale hierarchical image database. In IEEE Conference on Computer Vision and Pattern Recognition , pages 248-255. IEEE, 2009.

Zhijie Deng, Feng Zhou, and Jun Zhu. Accelerated linearized Laplace approximation for Bayesian deep learning. Advances in Neural Information Processing Systems , 35:2695-2708, 2022.

Bolei Zhou, Agata Lapedriza, Jianxiong Xiao, Antonio Torralba, and Aude Oliva. Learning deep features for scene recognition using places database. Advances in Neural Information Processing Systems , 27, 2014.

Tianlin Liu, Jose Antonio Lara Benitez, Florian Faucher, AmirEhsan Khorashadizadeh, Maarten V de Hoop, and Ivan Dokmani´ c. WaveBench: Benchmarks datasets for modeling linear wave propagation PDEs. Transactions on Machine Learning Research , 2023.

Peter Deuflhard, Andreas Hohmann, Peter Deuflhard, and Andreas Hohmann. Three-term recurrence relations. Numerical Analysis in Modern Scientific Computing: An Introduction , pages 151-178, 2003.

Peter Deuflhard. On algorithms for the summation of certain special functions. Computing , 17:37-48, 1976.

Simon Bartels, Kristoffer Stensbo-Smidt, Pablo Moreno-Mu˜ noz, Wouter Boomsma, Jes Frellsen, and Soren Hauberg. Adaptive Cholesky Gaussian processes. In International Conference on Artificial Intelligence and Statistics , pages 408-452. PMLR, 2023.

Rui Camachol. Inducing models of human control skills. In Machine Learning: ECML-98: 10th European Conference on Machine Learning Chemnitz, Germany, April 21-23, 1998 Proceedings 10 , pages 107-118. Springer, 1998.

Anton Schwaighofer and Volker Tresp. Transductive and inductive methods for approximate Gaussian process regression. Advances in Neural Information Processing Systems , 15, 2002.

Paul Shannon, Andrew Markiel, Owen Ozier, Nitin S Baliga, Jonathan T Wang, Daniel Ramage, Nada Amin, Benno Schwikowski, and Trey Ideker. Cytoscape: a software environment for integrated models of biomolecular interaction networks. Genome research , 13(11):2498-2504, 2003.

P. J Prince and J. R. Dormand. High order embedded Runge-Kutta formulae. Journal of Computational and Applied Mathematics , 7(1):67-75, 1981.

Antonio Stanziola, Simon R Arridge, Ben T Cox, and Bradley E Treeby. j-Wave: An opensource differentiable wave simulator. SoftwareX , 22:101338, 2023.

David JC MacKay. Bayesian interpolation. Neural computation , 4(3):415-447, 1992.

Alexander Immer, Maciej Korzepa, and Matthias Bauer. Improving predictions of Bayesian neural nets via local linearization. In International Conference on Artificial Intelligence and Statistics , pages 703-711. PMLR, 2021.

Vardan Papyan. Traces of class/cross-class structure pervade deep learning spectra. Journal of Machine Learning Research , 21(252):1-64, 2020.

Costas Bekas, Effrosyni Kokiopoulou, and Yousef Saad. An estimator for the diagonal of a matrix. Applied Numerical Mathematics , 57(11-12):1214-1229, 2007.

Mahdi Pakdaman Naeini, Gregory Cooper, and Milos Hauskrecht. Obtaining well calibrated probabilities using Bayesian binning. In Proceedings of the AAAI Conference on Artificial Intelligence , volume 29, 2015.

Appendix: Overview

Some of the results in the main paper promised detailed information about setups, data, compute, or additional proofs. For example, the case study about partial differential equations involves a data generation process which will receive further explanation in this supplement.

The appendix provides the following details: Appendices A and F elaborate on Figure 3 and Table 2 respectively; Appendices B to E contain proofs for the main results; and Appendices G to J describe the setup used for the case studies. Notably, Appendix G describes how we implement low-memory matrix-vector products in JAX (to replicate what makes libraries like KeOps [82] so efficient), and Appendix I outlines a PDE data set similar to that by Liu et al. [92].

Code Most of the contributions of this paper pertain to differentiable implementations of numerical algorithms - at the heart of it are our reverse-mode differentiable Lanczos and Arnoldi iterations. We provide JAX code to reproduce all experiments at the URL

and have packaged all numerical methods in a JAX library that can be installed via

Next to Lanczos and Arnoldi, this includes variants of conjugate gradient methods [58] and pivoted Cholesky preconditioners [81] (which we used for Gaussian processes), low-memory kernel-matrixvector products (also Gaussian processes), efficient GGN-vector products (used for Bayesian neural networks), and matrix-free sampling algorithms to sample from Gaussian processes and Laplaceapproximated Bayesian neural networks (used for Gaussian processes and Bayesian neural networks). These methods are known in some form or another, but until now, they have all lacked a software implementation in the current JAX ecosystem (with some exceptions relating to conjugate gradients).

Compute All experiments before the case studies were run on CPU. The Gaussian process and differential equation case studies run on a V100 GPU, the Bayesian neural network one on a P100 GPU. The Gaussian process and Bayesian neural network studies run in a few hours, all other code finishes in a few minutes.

A Additional context for Figure 3

To create Figure 3, we load the 'bcsstk18' matrix from the SuiteSparse matrix collection [6365]. This matrix is symmetric and has 11,948 rows/columns and 149,090 nonzero entries. We implement matrix-vector products with jax.experimental.sparse , and use a Lanczos iteration without reorthogonalisation. We time the execution of the forward pass, as well as the backward pass with and without implementing a custom vector-Jacobian product (the custom vector-Jacobian product involves the adjoint). The results were shown in Figure 3, and displayed how rapidly the computational complexity of automatic differentiation increases, whereas the computational complexity of our custom gradient mirrors that of the forward pass. This figure showed how without our proposed gradients, differentiating through the Lanczos iteration is unfeasible.

To add to this benchmark, we repeat the same for the Arnoldi iteration and show both compilation and runtime for Lanczos and Arnoldi in Figure 7 (this includes the curves from Figure 3 again). We see

0

50

100

150

200

250

0.0

0.1

0.2

0.3

Wall time (sec)

Lanczos: Run time

Forward

Adjoint

Backprop

0

50

100

150

200

250

5

10

15

Wall time (sec)

Lanczos: Compile time

Forward

Adjoint

Backprop

0

50

100

150

200

250

0.0

0.5

1.0

1.5

Wall time (sec)

Forward

Adjoint

Backprop

0

50

100

150

200

250

5

10

15

Wall time (sec)

Forward

Adjoint

Backprop

the custom gradient, the compilation times remain constant for increasing Krylov-space depth K and runtimes increase rapidly, the reverse is true for the Arnoldi iteration. The adjoint method mirrors that of the forward pass in both benchmarks. In either case, the increasing memory requirements for backpropagation through Lanczos and Arnoldi without our proposed adjoints becomes apparent.

B Proof of Theorem 4.1

Here is how we derive the adjoints of the Arnoldi system. The structure is the usual: take the forward constraint, differentiate, add Lagrange multipliers ('transpose'), and identify the adjoint system.

B.1 Linearisation

The linearisation of Equation 12 is

To see this, apply the chain- and product rules to the original constraint in Equation 12.

B.2 Transposition

Let ρ = ρ ( Q,r, H, c ) ∈ R be a scalar function of the outputs. In the following, interpret vectors as N × 1 matrices and scalars as 1 × 1 matrices. The values of inner products and the realisations of ρ are the only scalars.

with the constraints

Solving the adjoint system, Z Q = 0 , Z H = 0 , Z r = 0 , and Z c = 0 as a function of Λ , λ, Γ , Σ , and γ , yields the desired ∇ A ρ = Λ Q ⊤ and ∇ v f = λc ⊤ . Theorem 4.1 is complete.

C Proof of Theorem 4.2

Recall that ρ = ρ ( x 1 , ..., x K +1 ; a 1 , ..., a K ; b 1 , ..., b K ) shall be a scalar/loss that depends on the output of the algorithm. Denote by ∇ x k ρ the gradient of ρ with respect to each Lanczos vector x k , and by ∇ a k ρ and ∇ b k ρ the gradients with respect to a k and b k respectively.

The differential of normalisation, i.e., the operation s ↦→ h = s/ ( s ⊤ s ) is

The next steps are the usual ones: we start with the forward constraint, linearise, add Lagrange multipliers, and identify the adjoint system. The order of the middle two steps (linearise, multipliers) is interchangeable; while for Arnoldi, we linearise first and then add Lagrange multipliers, for Lanczos, we go the other way.

Define Lagrange multipliers { λ k } K k =0 ⊆ R n and { µ k / 2 , ν k } K j,k =1 ⊆ R ,

Differentiate and use that the forward constraint must be satisfied,

Sort all terms by differential,

so that enforcing that all Z a k , Z b k , Z x k terms are zero yields constraints for the multipliers from which we can compute gradients with respect to v and A .

What are those terms? Let λ K +1 = 0 , µ 0 = 0 , and ν 0 = 0 (to simplify notation below); then,

The expressions are like the forward-Lanczos constraints, and the main differences are (i) that the recursions are run backwards in 'time' and (ii) the existence of a nonzero bias term in the adjoints (marked by parentheses). Enforcing Z a k , Z b k , Z x k to be zero identifies

Theorem 4.2 is complete.

D Proof of Corollary 4.3

The following derivation covers only the case for Lanczos, i.e., we use the variables x 1 , ..., x K +1 instead of Arnoldi's q 1 , ..., q K . But the derivation is the same for both methods.

The expression we manipulate is

where all nond A -related quantities are treated as some unimportant constants.

For a single parameter θ j , d A = ( ∇ θ j A ) ⊤ d θ j and we have

In conclusion, the derivative of ρ wrt θ j is

and stacking all of those partial derivatives on top of each other, we obtain

We already compute A ( θ ) ⊤ λ k during the backward pass, so we are a single vector-Jacobian product with x k away from a matrix-parameter-gradient instead of a matrix-gradient. This requires O ( p + n ) storage, and is computed online, which makes the memory-complexity independent of K .

E Solving the adjoint system

The upcoming section details how to solve the adjoint system for both, the Lanczos and the Arnoldi iterations. It reuses notation from Appendices B and C.

We begin with Lanczos, because the solution is less technical, and because starting with Lanczos can provide a template for solving Arnoldi's adjoint system. All results in the present section (except for those that explicitly point to Deuflhard et al. [93], Deuflhard [94], which are marked as such) are new and a contribution of this work.

E.1 Lanczos

The inputs to the adjoint system are the Lanczos vectors { x k } K +1 k =1 and the coefficients { a k } K k =1 as well as { a k } K k =1 from the forward pass, the corresponding input derivatives {∇ x k ρ } K +1 k =1 , {∇ a k ρ } K k =1 , and {∇ a k ρ } K k =1 , and matrix A and initial vector v .

The overall strategy for solving the adjoint system of the Lanczos iteration (Theorem 4.2) is the following: for every k = K,..., 1 , alternate the two steps:

Combine orthogonality with the Z a k constraints to get ν k , and combine it with the Z b k constraints to get µ k .

Once each µ k and ν k are available, solve for λ k and repeat with the next lower k .

This results in the following procedure: To start, set ζ K +1 = -( ∇ x K +1 ρ ) and λ K +1 = 0 . Then, for all k = K,..., 1 , compute

Finally, set λ 0 = ζ 1 . Only λ and ζ affect subsequent steps; µ , ν , and ξ are only needed for computing λ and ζ . The k -th step depends on a k , b k , x k , x k +1 , ∇ a k ρ, ∇ b k ρ, ∇ x k ρ .

The strategy above yields all { λ k } K k =0 . Finalise the gradients

which can be embedded into any reverse-mode algorithmic-differentiation-engine.

E.2 Arnoldi

The process for Arnoldi is similar to that for Lanczos, but the derivation is more technical. It shares many similarities with deriving the Arnoldi iteration (i.e., the forward pass), so we begin by providing a perspective on recurrence relations (which include the Arnoldi iteration) through the lens of linear system solvers [93, 94] before we use this perspective to solve the adjoint system.

E.2.1 Solving the original system

At its core, finding the Arnoldi vectors amounts to solving

which is possible in closed form as follows: We rewrite the first two constraints as

This expression is equivalent to

This is similar to the work by Deuflhard [94], who explain adjoints of three-term recurrence relations. Since c 2 = ⟨ v, v ⟩ holds (ie, c is known), the first row of Q is known. Then, the first row of Q together with the orthogonality constraints yields the first row of H ⊤ , which then defines the next row of the linear system thus the second row of Q . Alternating between deriving the next row of H ⊤ and solving the lower triangular systems is then Arnoldi's algorithm:

Algorithm E.1 (Arnoldi's forward pass; paraphrased) . Assume that v and K are known. Compute c = √ ⟨ v, v ⟩ . Then, for k = 1 , ..., K , alternate the following tsteps:

Derive the next column of H using the orthogonality constraints.

Forward-substitute ('solve') the block-lower-triangular system for the next column of Q (respectively r at the last iteration).

Return all Q and H , as well as c and r .

The same principle applies to the adjoint system, and the only difference is that the notation is slightly more complicated:

E.2.2 Solving the adjoint system

The constraints Z Q = 0 and Z r = 0 mirror those of AQ -QH -r ( e K ) ⊤ = 0 and Qe 1 -cv = 0 ; the constraints Z H = 0 and Z c = 0 mirror the orthogonality constraints Q ⊤ Q = I and Q ⊤ r = 0 . Therefore, we start with Z Q = 0 and Z r = 0 ,

Introduce the auxiliary quantities

Ψ and ψ only serve the purpose of simplifying the notation in the coming part; there is no 'meaning' associated with them. Vectorise both expressions,

and observe that this can be written as a linear system

with a system matrix that is the transpose of the system matrix of the forward pass. The matrix is upper triangular, and the equation can be solved with backward substitution provided ψ ( γ ) and Ψ(Γ , γ ) are known.

The defining quantities Ψ and ψ emerge by combining the adjoint recursion with the projection constraints Z H = 0 (for Γ , which yields Ψ ) and Z r = 0 (for γ , which yields ψ ). We use Z c = 0 to get a single element in Γ ; more on this below. Summarise the adjoint pass:

Algorithm E.2 (Arnoldi's adjoint pass; paraphrased) . Assume Q , H , c , and r as well as the gradients of f with respect to those quantities. Then, compute ψ via computing γ using Z r = 0 . Then, for k = K,..., 1 , alternate the following two steps:

Derive the next row of Ψ by combining Z Q = 0 with the projection constraint Z H = 0

Backward-substitute ('solve') for the next row of Λ (recall: we loop backwards)

Finally, use Z c = 0 to get the first row of Ψ and solve for λ . Then, return ∇ A f = Λ Q ⊤ and ∇ v f = λc ⊤ .

The structure of the adjoint pass is similar to the forward pass (Table 6). In the following, we will elaborate on each of those steps. We assume that the reader knows how to solve a lower triangular linear system. We focus on constructing ψ and Ψ via Γ and γ .

E.2.3 Initialisation

Initialisation of the adjoint pass implies computing ψ . To get ψ , we need γ : Consider multiplying Z r with Q ⊤ ,

where we use that the last column in I ≪ ◦ Σ consists entirely of zeros. All other quantities are known. Therefore, γ is isolated and we identify

Next, use this γ to build ψ ,

and the initialisation step is complete.

E.2.4 Recursion

With ψ in place, we get the last column of Λ . To get the next column of Λ , we need to derive the right-hand side Ψ . To get Ψ , we need Γ .

Multiply Q ⊤ Z Q to obtain

Since H is Hessenberg, ( I ≪ ◦ Σ) H ⊤ is strictly lower triangular. Therefore, multiplication with I ≥ removes Σ from the expression,

The term involving λ can be simplified as follows: Due to the presence of ( e 1 ) ⊤ , we know that Q ⊤ λ ( e 1 ) ⊤ is lower triangular (in fact, it has a single nonzero column). Thus, I ≥ ◦ ( Q ⊤ λ ( e 1 ) ⊤ ) is proportional to e 1 ( e 1 ) ⊤ ,

and all quantities are known; hence,

Algorithm E.3 (Forward pass) . Initialise k = 1 , Qe 1 . Then, for k = 1 , ..., K :

Use orthogonality for a new row in the system matrix in Equation 39.

Solve for the next column of Q

Optional: re-enforce Q ⊤ Q = I .

Solve for r and return Q,H,r,c .

Algorithm E.4 (Backward pass) . Initialise k = K , Λ e 1 . Then, for k = K,..., 1 :

Use projection for a new column of the right-hand side Ψ

Solve for the next column of Λ

Optional: re-enforce Z H = 0 .

Solve for λ and return ∇ θ ρ and ∇ v ρ .

must hold.

Now, the most important observation is the following: the last column of I = ◦ Γ+ I ≥ ◦ Γ ⊤ depends on the last column of Q ⊤ A ⊤ Λ and known quantities; the penultimate column depends on the penultimate column of Γ , and so on. But at the time of assembling the last column of Γ , the last column of Λ is known! More generally, we always know one more column of Λ than of Γ , so we can recursively assemble I = ◦ Γ + I ≥ ◦ Γ ⊤ :

Let

Let us use it:

This yields the next row/column of Γ + Γ ⊤ , and therefore the next row of Ψ . From there, we can assemble the next column of Λ and iterate. Figure 8 (respectively Algorithms E.3 and E.4) compare pseudocode for forward and adjoint passes. Altogether, the implementation of the adjoint pass is very similar to that of the forward pass.

At the final step, we obtain not the last column of Λ but λ , though this is a byproduct of solving the triangular linear system. It does not need further explanation.

Remark E.5 ( Σ ) . Like for gradients of QR decompositions [61, 75], we never solve for Σ .

F Setup for Table 2

To create Table 2, we implement an operator

where ( H,Q,r,c ) are the result of a full-rank Arnoldi iteration (i.e. K = N ). For K = N , QHQ ⊤ = A and I must have an identity Jacobian; thus,

measures the loss of accuracy when differentiating the Arnoldi iteration. A small ε is desirable.

Then, using double-precision, we construct a Hilbert matrix A = [1 / ( i + j +1)] N i,j =1 ∈ R N × N which is a famously ill-conditioned matrix and a common test-bed for

2

4

6

8

10

18

10

14

10

10

10

6

10

2

Loss of accuracy

Adj. w/ re-proj.

Adj. w/o re-proj.

Backprop

the loss of orthogonality in methods like the Lanczos and Arnoldi iteration [e.g. 71, Table 7.1]. We evaluate three algorithms, all of which rely on the Arnoldi iteration with full reorthogonalisation on the forward-pass: One algorithm does not re-project on the adjoint constraints, another one does, and

be a symmetrisation operator. We define it for the sole purpose of reconstructing

Matvec run times(sec)vs.size of dataset

GPyTorch (via Keops)

Ours (via map)

Run time (sec)

10-1

Ours (via vmap) K=10

Ours (via vmap) K=100

10-2

10-3

102

103

104

Datasetsize

for reference we compute ε when 'backpropagating through' the re-orthogonalised Arnoldi iteration as a third option. Figure 3 has demonstrated that the first two options beat the third one in terms of speed, but we consider numerical accuracy here.

We evaluate ε for N = 1 , ..., 8 (see Figure 9), and show the values for N = 8 in Table 2. The numerical accuracy of the re-projected adjoint method matches that of differentiating 'through' re-orthogonalisation, and outperforms not re-projecting by a margin.

G Memory-efficient kernel-matrix-vector products in JAX

Matrix-free linear algebra requires efficient matrix-vector products. For kernel function k = k ( x, x ′ ) , and input data x 1 , ..., x N , Gaussian process covariance matrices are of the form A = [ k ( x i , x j )] N i,j =1 . Matrix-vector products with A thus look like

and can be assembled row-wise, either sequentially or parallely.

The more rows we assemble in parallel, the faster the runtime but also the higher the memory requirements, so we follow Gardner et al. [6] and choose the largest number of rows of A that still fit into memory, say r such rows, and assemble Av in blocks of r . In practice, we implement this in JAX by combining jax.lax.map and jax.vmap , but care has to be taken with reverse-mode automatic differentiation through ( v, θ ) ↦→ A ( θ ) v because by default, reverse-mode differentiation stores all intermediate results. To solve this problem, we place checkpoints around each such batch of rows, which reduces the memory requirements but roughly doubles the runtime. (We place another checkpoint around each stochastic trace-estimation sample, which roughly doubles the runtime again.)

An alternative to doing this manually is the KeOps library [82], which GPyTorch [6] builds on. However, there currently exists no JAX-compatible interface to KeOps which is why we have to implement the above solution.

Figure 10 compares the runtime of our approach to that of KeOps custom CUDA code. We see that we are competitive, but roughly 5 × slower for medium to large datasets. Multiplying this with the 4 × increase due to the checkpoints discussed above explains the 20 × increase in runtime compared to GPyTorch. Being 20 × slower than GPyTorch per epoch is only due to the matrix-vector products, and has nothing to do with the algorithm contribution. Future work should explore closing this gap with a KeOps-to-JAX interface.

H Experiment configurations for the Gaussian process study

Data For the experiments we use the 'Protein', 'KEGG (undirected', 'KEGG (directed)', 'Elevators', and 'Kin40k' datasets (Table 7, adapted from Bartels et al. [95]). All are part of the UCI data

repository, and accessible through there.

The data is subsampled to admit the train/test split of 80/20%, and to admit an even division into the number of row partitions. More specifically, we use 10 partitions for the kernel-matrix vector products. This way, we have to discard less than 1% of the data; e.g., on KEGG (undir), we use 63,600 instead of the original 63,608 points.

We calibrate a Mat´ ern prior with smoothness ν = 1 . 5 , using 10 matrix-vector products per Lanczos iteration, conjugate gradients tolerance of ϵ = 1 , a rank-15 pivoted Cholesky preconditioner, and 10 Rademacher samples. We evaluate all samples sequentially (rematerialising on the backward pass to save memory, as discussed in Appendix G). The conjugate-gradients tolerances are taken to be absolute (instead of relative), and the parametrisations of the Gaussian process models and loss functions match that of GPyTorch.

For every model, we calibrate an independent lengthscale for each input dimension, as well as an scalar observation noise, scalar output-scale, and the value of a constant prior mean. All parameters are initialised randomly. We use the Adam optimiser with learning rate 0.05 for 75 epochs. All experiments are repeated for three different seeds.

I Partial differential equation data

We generate data for the differential equations as follows: Recall the problem setup of a partial differential equation

with Neumann boundary conditions. The coefficient field ω is space- but not time-dependent.

First, we discretise the Laplacian operator with central differences on an equidistant, tensor-product mesh that consists of 128 points per dimension, which yields 128 2 grid points. The resulting second-order ordinary differential equation

where M is the discretised Laplacian, is then transformed into a first-order differential equation

This equation is solved by the matrix exponential, and the system matrix A is asymmtric (by construction), and highly sparse because M is. Matrix-vector products with A are cheap, because we can implement them with jax.scipy.signal.convolve2d .

Then, we sample a true ω from a Gaussian process with a square-exponential covariance kernel, using lengthscale softplus ( -0 . 75) and output-scale softplus ( -10) . We sample from this process with the Lanczos algorithm [11] using Krylov-depth K = 32 .

Then, we use another Gaussian process with the same kernel, but lengthscale softplus (0) and output scale softplus (0) , to sample 256 initial distributions - again with the Lanczos algorithm

0.0

0.5

1.0

0.0

0.5

1.0

Inputs

0.0

0.5

1.0

0.0

0.5

1.0

0.0

0.5

1.0

0.0

0.5

1.0

0.0

0.5

1.0

0.0

0.5

1.0

Targets

0.0

0.5

1.0

0.0

0.5

1.0

0.0

0.5

1.0

0.0

0.5

1.0

0.2

0.0

0.2

0.4

0.6

0.8

1.0

1.2

1.4

1.0

0.5

0.0

0.5

1.0

1.5

2.0

2.5

3.0

1.00

0.75

0.50

0.25

0.00

0.25

0.50

0.75

1.00

3.5

3.0

2.5

2.0

1.5

1.0

0.5

0.0

0.5

1.2

0.9

0.6

0.3

0.0

0.3

0.6

0.9

1.2

7.5

6.0

4.5

3.0

1.5

0.0

1.5

3.0

4.5

6.0

[11]. These 256 initial conditions are solved with Diffrax's implementation of Dopri8 [99] using 128 timesteps. Some example input/output pairs are in Figure 11.

This setup is similar to that of the WaveBench dataset [92], with the main difference being that the WaveBench dataset uses a slightly different formulation of the wave equation. 4 We use the one above because it lends itself more naturally to matrix exponentials, which are at the heart of this experiment.

J Implementation details for the Bayesian neural network study

J.1 Bayesian neural networks with Laplace approximations

Another possible application of the gradients of matrix functions is marginal-likelihood-based optimisation of Bayesian Neural Networks. Suppose g θ ( x ) is the output of a neural network with parameters θ ∈ R P . The choice of the model shall be denoted by M and consist of both continuous and discrete hyperparameters (such as network architecture, likelihood precision, prior precision, etc.). For some choice of prior given by

we can specify a Bayesian model. The posterior distribution is then given by:

The marginal likelihood is given by normalizing constant of this posterior, i.e.

As suggested by MacKay [101], this marginal likelihood can be used for model selection in Bayesian neural networks. Immer et al. [30] use the Laplace approximation of the posterior to obtain access to the marginal likelihood of the Bayesian neural network and its stochastic gradients.

The Laplace approximation of the marginal likelihood is given by:

where H θ MAP = -∇ 2 θ log p ( y, θ MAP | x, M ) . Usual choices of the prior are N (0 , α -1 I ) . Usually this Hessian is approximated with the generalized Gauss-Newton (GGN) matrix [102]

and likelihood

where D 2 ρ is the Hessian of the loss, and D θ g the Jacobian of g (recall Equation 2). This objective is used to optimize the prior precision of the model or any continuous model hyperparameters. Matrix-vector products with the GGN matrix can be accessed through automatic differentiation using Jacobian-vector and vector-Jacobian products. With these efficient matrix-vector products, one can estimate the log-determinant of GGN using matrix-free techniques like the Lanczos iteration.

To make predictions using the Laplace approximation of the posterior, we also need to sample from the normal distribution N ( θ MAP , A -1 ) . Samples from this distribution can be written as:

where ϵ ∼ N (0 , I ) . The main bottleneck in this computation is the inversion and matrix square root of the GGN matrix, and we implement it with a Lanczos iteration using f ( x ) = x -1 / 2 . Since the GGN is empirically known to have low-rank [103], doing a few Lanczos iterations can get us close to an accurate estimation.

J.2 Experiment setup

We estimate the diagonal of the GGN stochastically via (' ◦ ' is the element-wise product) [104]

We use 150 matrix-vector products for both diagonal calibration and our Lanczos-based estimation. We use 30 Monte-Carlo samples to estimate the log-likelihoods for evaluating the test metrics, and we use places365 [91] as an out-of-distribution dataset to compute OOD-AUROC. We also compute the expected calibration error (ECE) [105] of the model.

Data: We show scalability by doing Laplace approximation on Imagenet1k image classification [89]. The training set consists of approximately 1.2 million images, each belonging to one of 1000 classes. We find that we can take small subsets of this dataset and still converge to the same prior precision. Our computational budget allows us to use 10 percent of the samples for each class. However, even for very small subsamples of the data, we converge to a very similar prior precision.

Method: To optimize the prior precision we use the marginal likelihood as the objective. We use the RMSprop optimizer with a learning rate of 0.01 for 100 epochs for optimizing both the diagonal and Lanczos approximations of the GGN.

NeurIPS Paper Checklist

1. Claims

Question: Do the main claims made in the abstract and introduction accurately reflect the paper's contributions and scope?

Answer: [Yes]

Justification: The main contributions, adjoint systems for the Lanczos and Arnoldi iterations, are explained in Section 4. The three case studies are in Sections 5 to 7.

Guidelines:

The answer NA means that the abstract and introduction do not include the claims made in the paper.

The abstract and/or introduction should clearly state the claims made, including the contributions made in the paper and important assumptions and limitations. A No or NA answer to this question will not be perceived well by the reviewers.

The claims made should match theoretical and experimental results, and reflect how much the results can be expected to generalize to other settings.

It is fine to include aspirational goals as motivation as long as it is clear that these goals are not attained by the paper.

2. Limitations

Question: Does the paper discuss the limitations of the work performed by the authors?

Answer: [Yes]

Justification: The limitations are discussed in the paragraph titled 'Limitations and future work' on page 4. All assumptions (i.e., Assumptions 3.1 and 3.2) are contextualised in the sentences before and after they are have been introduced.

Guidelines:

The answer NA means that the paper has no limitation while the answer No means that the paper has limitations, but those are not discussed in the paper.

The authors are encouraged to create a separate 'Limitations' section in their paper.

The paper should point out any strong assumptions and how robust the results are to violations of these assumptions (e.g., independence assumptions, noiseless settings, model well-specification, asymptotic approximations only holding locally). The authors should reflect on how these assumptions might be violated in practice and what the implications would be.

The authors should reflect on the scope of the claims made, e.g., if the approach was only tested on a few datasets or with a few runs. In general, empirical results often depend on implicit assumptions, which should be articulated.

The authors should reflect on the factors that influence the performance of the approach. For example, a facial recognition algorithm may perform poorly when image resolution is low or images are taken in low lighting. Or a speech-to-text system might not be used reliably to provide closed captions for online lectures because it fails to handle technical jargon.

The authors should discuss the computational efficiency of the proposed algorithms and how they scale with dataset size.

If applicable, the authors should discuss possible limitations of their approach to address problems of privacy and fairness.

While the authors might fear that complete honesty about limitations might be used by reviewers as grounds for rejection, a worse outcome might be that reviewers discover limitations that aren't acknowledged in the paper. The authors should use their best judgment and recognize that individual actions in favor of transparency play an important role in developing norms that preserve the integrity of the community. Reviewers will be specifically instructed to not penalize honesty concerning limitations.

3. Theory Assumptions and Proofs

Question: For each theoretical result, does the paper provide the full set of assumptions and a complete (and correct) proof?

Answer: [Yes]

Justification: The main contributions, Theorems 4.1 and 4.2 and Corollary 4.3, are proven in Appendices B to D. Appendix E discusses solving the adjoint system in full detail.

Guidelines:

The answer NA means that the paper does not include theoretical results.

All the theorems, formulas, and proofs in the paper should be numbered and crossreferenced.

All assumptions should be clearly stated or referenced in the statement of any theorems.

The proofs can either appear in the main paper or the supplemental material, but if they appear in the supplemental material, the authors are encouraged to provide a short proof sketch to provide intuition.

Inversely, any informal proof provided in the core of the paper should be complemented by formal proofs provided in appendix or supplemental material.

Theorems and Lemmas that the proof relies upon should be properly referenced.

4. Experimental Result Reproducibility

Question: Does the paper fully disclose all the information needed to reproduce the main experimental results of the paper to the extent that it affects the main claims and/or conclusions of the paper (regardless of whether the code and data are provided or not)?

Answer: [Yes]

Justification: The most important information about the experiment setup is a part of the main paper in Sections 5 to 7; further information can be found in Appendices G to J. Appendices A and F discuss the setup for Figure 3 and Table 2. Code will be published upon acceptance.

Guidelines:

The answer NA means that the paper does not include experiments.

If the paper includes experiments, a No answer to this question will not be perceived well by the reviewers: Making the paper reproducible is important, regardless of whether the code and data are provided or not.

If the contribution is a dataset and/or model, the authors should describe the steps taken to make their results reproducible or verifiable.

Depending on the contribution, reproducibility can be accomplished in various ways. For example, if the contribution is a novel architecture, describing the architecture fully might suffice, or if the contribution is a specific model and empirical evaluation, it may be necessary to either make it possible for others to replicate the model with the same dataset, or provide access to the model. In general. releasing code and data is often one good way to accomplish this, but reproducibility can also be provided via detailed instructions for how to replicate the results, access to a hosted model (e.g., in the case of a large language model), releasing of a model checkpoint, or other means that are appropriate to the research performed.

While NeurIPS does not require releasing code, the conference does require all submissions to provide some reasonable avenue for reproducibility, which may depend on the nature of the contribution. For example

(a) If the contribution is primarily a new algorithm, the paper should make it clear how to reproduce that algorithm.

(b) If the contribution is primarily a new model architecture, the paper should describe the architecture clearly and fully.

(c) If the contribution is a new model (e.g., a large language model), then there should either be a way to access this model for reproducing the results or a way to reproduce the model (e.g., with an open-source dataset or instructions for how to construct the dataset).

(d) We recognize that reproducibility may be tricky in some cases, in which case authors are welcome to describe the particular way they provide for reproducibility. In the case of closed-source models, it may be that access to the model is limited in some way (e.g., to registered users), but it should be possible for other researchers to have some path to reproducing or verifying the results.

5. Open access to data and code

Question: Does the paper provide open access to the data and code, with sufficient instructions to faithfully reproduce the main experimental results, as described in supplemental material?

Answer: [Yes]

Justification: Code has been submitted as a part of the supplementary material, and will be published upon acceptance.

Guidelines:

The answer NA means that paper does not include experiments requiring code.

Please see the NeurIPS code and data submission guidelines ( https://nips.cc/ public/guides/CodeSubmissionPolicy ) for more details.

While we encourage the release of code and data, we understand that this might not be possible, so 'No' is an acceptable answer. Papers cannot be rejected simply for not including code, unless this is central to the contribution (e.g., for a new open-source benchmark).

The instructions should contain the exact command and environment needed to run to reproduce the results. See the NeurIPS code and data submission guidelines ( https: //nips.cc/public/guides/CodeSubmissionPolicy ) for more details.

The authors should provide instructions on data access and preparation, including how to access the raw data, preprocessed data, intermediate data, and generated data, etc.

The authors should provide scripts to reproduce all experimental results for the new proposed method and baselines. If only a subset of experiments are reproducible, they should state which ones are omitted from the script and why.

At submission time, to preserve anonymity, the authors should release anonymized versions (if applicable).

Providing as much information as possible in supplemental material (appended to the paper) is recommended, but including URLs to data and code is permitted.

6. Experimental Setting/Details

Question: Does the paper specify all the training and test details (e.g., data splits, hyperparameters, how they were chosen, type of optimizer, etc.) necessary to understand the results?

Answer: [Yes]

Justification: See the answer to '4. Experimental Result Reproducibility' above.

Guidelines:

The answer NA means that the paper does not include experiments.

The experimental setting should be presented in the core of the paper to a level of detail that is necessary to appreciate the results and make sense of them.

The full details can be provided either with the code, in appendix, or as supplemental material.

7. Experiment Statistical Significance

Question: Does the paper report error bars suitably and correctly defined or other appropriate information about the statistical significance of the experiments?

Answer: [Yes]

Justification: All case studies report mean and standard deviations of multiple runs. The only exception is the Bayesian neural network example, which uses a single training run (but evaluates test metrics on multiple seeds).

Guidelines:

The answer NA means that the paper does not include experiments.

The authors should answer 'Yes' if the results are accompanied by error bars, confidence intervals, or statistical significance tests, at least for the experiments that support the main claims of the paper.

The factors of variability that the error bars are capturing should be clearly stated (for example, train/test split, initialization, random drawing of some parameter, or overall run with given experimental conditions).

The method for calculating the error bars should be explained (closed form formula, call to a library function, bootstrap, etc.)

The assumptions made should be given (e.g., Normally distributed errors).

It should be clear whether the error bar is the standard deviation or the standard error of the mean.

It is OK to report 1-sigma error bars, but one should state it. The authors should preferably report a 2-sigma error bar than state that they have a 96% CI, if the hypothesis of Normality of errors is not verified.

For asymmetric distributions, the authors should be careful not to show in tables or figures symmetric error bars that would yield results that are out of range (e.g. negative error rates).

If error bars are reported in tables or plots, The authors should explain in the text how they were calculated and reference the corresponding figures or tables in the text.

8. Experiments Compute Resources

Question: For each experiment, does the paper provide sufficient information on the computer resources (type of compute workers, memory, time of execution) needed to reproduce the experiments?

Answer: [Yes]

Justification: The introductory part of the appendix contains a paragraph titled 'Compute'.

Guidelines:

The answer NA means that the paper does not include experiments.

The paper should indicate the type of compute workers CPU or GPU, internal cluster, or cloud provider, including relevant memory and storage.

The paper should provide the amount of compute required for each of the individual experimental runs as well as estimate the total compute.

The paper should disclose whether the full research project required more compute than the experiments reported in the paper (e.g., preliminary or failed experiments that didn't make it into the paper).

9. Code Of Ethics

Question: Does the research conducted in the paper conform, in every respect, with the NeurIPS Code of Ethics https://neurips.cc/public/EthicsGuidelines ?

Answer: [Yes]

Justification: We use datasets that are either self-created (Section 6 and Appendix I), or common test-cases for machine learning methods (UCI datasets, ImageNet) or numerical algorithms (SuiteSparse matrix collection).

Guidelines:

The answer NA means that the authors have not reviewed the NeurIPS Code of Ethics.

If the authors answer No, they should explain the special circumstances that require a deviation from the Code of Ethics.

The authors should make sure to preserve anonymity (e.g., if there is a special consideration due to laws or regulations in their jurisdiction).

10. Broader Impacts

Question: Does the paper discuss both potential positive societal impacts and negative societal impacts of the work performed?

Answer: [No]

Justification: This research provides a foundational algorithm for computational sciences, and societal impact is difficult if not impossible to predict.

Guidelines:

The answer NA means that there is no societal impact of the work performed.

If the authors answer NA or No, they should explain why their work has no societal impact or why the paper does not address societal impact.

Examples of negative societal impacts include potential malicious or unintended uses (e.g., disinformation, generating fake profiles, surveillance), fairness considerations (e.g., deployment of technologies that could make decisions that unfairly impact specific groups), privacy considerations, and security considerations.

The conference expects that many papers will be foundational research and not tied to particular applications, let alone deployments. However, if there is a direct path to any negative applications, the authors should point it out. For example, it is legitimate to point out that an improvement in the quality of generative models could be used to generate deepfakes for disinformation. On the other hand, it is not needed to point out that a generic algorithm for optimizing neural networks could enable people to train models that generate Deepfakes faster.

The authors should consider possible harms that could arise when the technology is being used as intended and functioning correctly, harms that could arise when the technology is being used as intended but gives incorrect results, and harms following from (intentional or unintentional) misuse of the technology.

If there are negative societal impacts, the authors could also discuss possible mitigation strategies (e.g., gated release of models, providing defenses in addition to attacks, mechanisms for monitoring misuse, mechanisms to monitor how a system learns from feedback over time, improving the efficiency and accessibility of ML).

11. Safeguards

Question: Does the paper describe safeguards that have been put in place for responsible release of data or models that have a high risk for misuse (e.g., pretrained language models, image generators, or scraped datasets)?

Answer: [NA]

Justification: This paper does not contribute data or models that would require safeguards.

Guidelines:

The answer NA means that the paper poses no such risks.

Released models that have a high risk for misuse or dual-use should be released with necessary safeguards to allow for controlled use of the model, for example by requiring that users adhere to usage guidelines or restrictions to access the model or implementing safety filters.

Datasets that have been scraped from the Internet could pose safety risks. The authors should describe how they avoided releasing unsafe images.

We recognize that providing effective safeguards is challenging, and many papers do not require this, but we encourage authors to take this into account and make a best faith effort.

12. Licenses for existing assets

Question: Are the creators or original owners of assets (e.g., code, data, models), used in the paper, properly credited and are the license and terms of use explicitly mentioned and properly respected?

Answer: [Yes]

Justification: All assets used in the experiments have been cited. See also the answer to '9. Code of Ethics'.

Guidelines:

The answer NA means that the paper does not use existing assets.

The authors should cite the original paper that produced the code package or dataset.

The authors should state which version of the asset is used and, if possible, include a URL.

The name of the license (e.g., CC-BY 4.0) should be included for each asset.

For scraped data from a particular source (e.g., website), the copyright and terms of service of that source should be provided.

If assets are released, the license, copyright information, and terms of use in the package should be provided. For popular datasets, paperswithcode.com/datasets has curated licenses for some datasets. Their licensing guide can help determine the license of a dataset.

For existing datasets that are re-packaged, both the original license and the license of the derived asset (if it has changed) should be provided.

If this information is not available online, the authors are encouraged to reach out to the asset's creators.

13. New Assets

Question: Are new assets introduced in the paper well documented and is the documentation provided alongside the assets?

Answer: [Yes]

Justification: The code (attached to this submission) is documented. The appendices contain all other information.

Guidelines:

The answer NA means that the paper does not release new assets.

Researchers should communicate the details of the dataset/code/model as part of their submissions via structured templates. This includes details about training, license, limitations, etc.

The paper should discuss whether and how consent was obtained from people whose asset is used.

At submission time, remember to anonymize your assets (if applicable). You can either create an anonymized URL or include an anonymized zip file.

14. Crowdsourcing and Research with Human Subjects

Question: For crowdsourcing experiments and research with human subjects, does the paper include the full text of instructions given to participants and screenshots, if applicable, as well as details about compensation (if any)?

Answer: [NA]

Justification: This study does not involve crowdsourcing nor human subjects.

Guidelines:

The answer NA means that the paper does not involve crowdsourcing nor research with human subjects.

Including this information in the supplemental material is fine, but if the main contribution of the paper involves human subjects, then as much detail as possible should be included in the main paper.

According to the NeurIPS Code of Ethics, workers involved in data collection, curation, or other labor should be paid at least the minimum wage in the country of the data collector.

15. Institutional Review Board (IRB) Approvals or Equivalent for Research with Human Subjects

Question: Does the paper describe potential risks incurred by study participants, whether such risks were disclosed to the subjects, and whether Institutional Review Board (IRB) approvals (or an equivalent approval/review based on the requirements of your country or institution) were obtained?

Answer: [NA]

Justification: This paper does not involve crowdsourcing nor research with human subjects.

Guidelines:

The answer NA means that the paper does not involve crowdsourcing nor research with human subjects.

Depending on the country in which research is conducted, IRB approval (or equivalent) may be required for any human subjects research. If you obtained IRB approval, you should clearly state this in the paper.

We recognize that the procedures for this may vary significantly between institutions and locations, and we expect authors to adhere to the NeurIPS Code of Ethics and the guidelines for their institution.

For initial submissions, do not include any information that would break anonymity (if applicable), such as the institution conducting the review.

Peer reviews:
{"IS_META_REVIEW": false, "comments": "SUMMARY:\nThis paper introduces a new matrix free method for automatically differentiating functions of matrices. The computational problem discussed in this paper is of interest because the matrix dimension scales with respect to the size of the dataset (e.g. Gaussian process regression, etc.). The authors' algorithm yields the exact gradients of the forward pass, all gradients are obtained with the same code, and said code runs in linear time- and memory-complexity. The proposed method is also matrix-free and does not form the matrix explicitly which is the key to scalability. The authors' method evaluate functions of large matrices by: 1) first decomposing the matrix into a product of small matrices (e.g. Lanczos, Arnoldi iterations); 2) then evaluating functions on the small matrix produced during the Lanczos/Arnoldi iteration. The authors note that functions of small matrices can be differentiated efficiently. The authors provide the method to compute gradients of the Lanczos/Arnoldi iteration so that backpropagation can be implemented efficiently. The authors use differentiation via adjoints of the Lanczos/Anroldi iterations (this is described in Theorem 4.1 and Theorem 4.2). The parameter gradient expression that can be used for any problem is provided in Corollary 4.3. The authors provide experimental results which provide impressive speedup over GPyTorch over problems of interest including: Gaussian process, physics-informed PDEs, Bayesian neural network tuning.\n\nSTRENGTHS:\n1. This paper tackles an important computational bottleneck in tuning hyperparameters of potentially complex models that are used in scientific and machine learning applications.\n2. The proposed method is general and can accomodate any matrix functionals and do not need explicit derivations of the gradients.\n3. The authors provide experimental results on several problems of interest to machine learning practitioners.\n\nWEAKNESSES:\nThere are no particular weaknesses I found on reading the paper. The paper is well written.\n\nQUESTIONS:\n1. There are parallelization techniques that may be useful for even scaling up the proposed method.\n2. How many samples do you take for stochastic estimation of log-determinant for the exact Gaussian process result?\n3. What norm is the gradient error measured in?\n\nLIMITATIONS:\nThe authors describe several limitations - but as the authors mention, these extensions describe a more expanded write-up.", "TITLE": "Official Review", "RECOMMENDATION": 7, "REVIEWER_CONFIDENCE": 3, "SOUNDNESS_CORRECTNESS": 3, "DATE": "2024-06-29"}

comments: SUMMARY:
There are some useful iterative methods for calculating important matrix products, to wit, Lanczos and Arnoldi iterations, which apparently did not have known derivatives, until now. The paper provides a generic framework for calculating the derivatives of such iterative linear operator approximations. The core of the paper is interpreting the Lanczos resp Arnoldi iteration as an iterative system and using the implicit derivative trick

STRENGTHS:
While these results are not *world* shaking, they seem to provide immediate quality-of-life improvements to linear algebra users in high-value problems. The results unify several known "matrix free" tricks, which is satisfying, and point the way to more. 

The paper is well-written, compact, and easy to understand, which is a great relief this deep into the review process.

WEAKNESSES:
As far as I can see, few. The paper seems to present what I need to know.

It would not be impossible for these results to be known elsewhere in the literature, but if they are known, I have not seen them.

QUESTIONS:
I have no questions. This paper was well explained, and clear about its goals, and how it approached them.

LIMITATIONS:
There are many limitations to the methods divulged here, but they seem to be adequately articulated in the paper.
TITLE: Official Review
SOUNDNESS_CORRECTNESS: 3
DATE: 2024-07-11

{"IS_META_REVIEW": false, "comments": "SUMMARY:\nThe paper proposes an adjoint method for functions of matrices that utilize Arnoldi/Lanczos iterations to compute gradients with respect to large dimensional variables and demonstrates their approach's utility on a variety of common compute/memory intensive tasks encountered in machine learning. They derive the adjoints by implicitly differentiating the solution of Arnoldi/Lanczos iterations with respect to the input matrix and vector and then show how this can be used to compute gradients with respect to parameters that the input matrix depends on. They then examine their method on three case studies: Gaussian process hyperparameter optimization, solving for parameters of a discretized two-dimensional (in space) PDE and post-training calibration of a Bayesian neural network. Their results demonstrate an improvement over the standard approaches on a range of metrics.\n\nSTRENGTHS:\n- An adjoint method for the Arnoldi iteration is certainly a useful addition to the automatic differentiation toolbox given the techniques wide use and would thus be of significant interest to the Neurips community.\n- The paper was mostly clear to read and understand. The conciseness of the experiment section is also a strength as the key aspects of the setups and the results are succinctly presented.\n- The paper's results indicate the methods utility in obtaining better runtimes, more accurate gradients and/or lower train and test losses on a range of important tasks in machine learning. In particular, the BNN calibration experiment clearly demonstrates how their method can handle matrices that may be too large to fit on a GPU and so it doesn't have to resort to subsequent approximation which they show leads to better performance.\n\nWEAKNESSES:\n- Although the paper empirically shows how backprop through a matrix function is slower than their adjoint method for Arnoldi iterations in Fig 3, the fact that a sparse matrix (as opposed to a dense one) was utilized motivates some skepticism over whether we would expect to see this same runtime relationship for a dense matrix. In fact, the exact GP results suggest that implementing matrix-matrix (/-vector) operations more efficiently can be enough to make reverse-mode AD work quicker for dense matrices. More discussion on why the adjoint Arnoldi iteration is more appropriate would strengthen their argument for the improved efficiency of their method.\n- The description of the adjoint systems in section 4.1 is lacking some explanation to make clear the key aspects of the adjoint methods and why this is preferable over reverse-mode AD. Reverse-mode AD also only utilizes vector-Jacobian products and so is a kind of \"matrix-free\" method. Explanation of how their method differs from this would make more apparent their contribution.\n\nQUESTIONS:\n- The last part of the explanation of implicit differentiation in section 4 was confusing. On the one hand $\\mathrm{d}\\rho$ is defined in eqn (9) but the form $\\mathrm{d}\\rho = \\langle \\nabla_{\\theta} \\rho, \\mathrm{d}\\theta \\rangle$ is given on the following line. It was not clear as to why these two should be equal. Being more concrete on the definition of $\\rho$ would help here\n- As a solution to the second weakness listed above an algorithm comparing adjoint Arnoldi/Lanczos with reverse-mode AD may help to make clear the differences between the methods.\n- On the sentence starting with \"Gradients ...\" on line 198, doesn't reverse-mode AD also only use matrix-vector products as well?\n- A definition of \"loss of accuracy\" in Table 2 should probably be given in the main text.\n- A bit of discussion as to why the JAX low-memory matrix-vector product implementations cannot compete with KeOps would be a worthwhile addition to the paper.\n\nLIMITATIONS:\nLimitations on the conceptual aspect of the approach are discussed at the end of section 3 but some discussion in light of the experimental results would also be of value", "TITLE": "Official Review", "RECOMMENDATION": 7, "REVIEWER_CONFIDENCE": 4, "SOUNDNESS_CORRECTNESS": 3, "DATE": "2024-07-12"}

{"IS_META_REVIEW": false, "comments": "SUMMARY:\nThis paper proposes a new approach to perform automatic differentiation for function of large matrices. Specifically, the paper outlines the backward computation of the matrix-vector product f(A(\\theta)) * v where A(\\theta) is the jacobian of a large NN that will not fit into memory. The proposed approach uses the Lanczos and Arnoldi iteration method to factorize the matrix-vector product, which permits inexpensive backpropagation, and then derive the backward computation for the Lanczos and Arnoldi iteration via the adjoint method. This technique is tested in three different scenarios that require the evaluation of such matrix-vector product: Gaussian processes (GP), Physics Informed ML with PDE, and Bayesian NN.\n\nSTRENGTHS:\n- Theoretically interesting approach to auto diff of large Jacobian vector product\n- Potentially useful in scenarios where functions of large matrices are involved in the objective function\n- Interesting case studies detailing several such scenarios and how to apply the proposed method in those scenarios\n- Improved performance in majority of experiments\n- Generally clear and self-contained presentation, easy to read and follow\n\nWEAKNESSES:\n1. Motivation is somewhat unclear. The paper claims that the proposed method provides exact gradient of the forward pass, but it doesn't seem true when the Lanczos & Arnoldi iterations themselves do not yield an exact factorization (Eq. 7). This method, although theoretically quite interesting, should belong to the same class with other approximation methods. As such, I would like the authors to explicitly discuss the benefit of this approximation compared to previous work (which are currently positioned as being inferior to an exact gradient method)\n \n2. Empirical results are not convincing:\n- Table 3 seems to highlight the wrong improvement. It is moot to compare training loss when the loss landscapes are different. The real performance measure should be RMSE, in terms of which both methods converge to the same values (although the proposed Arnoldi method is 20x slower -- so I'm not sure what's the benefit here)\n- Case study 6 again shows the same performance between the Arnoldi method & Dopri5.\n- Bayesian NN is usually trained with Variational Inference. Diagonal method is a rather crude approximation, and it is not surprising that the proposed method outperforms it.\n\nQUESTIONS:\nI have no further question since the method is sound & clearly presented. My only problem is that the empirical results are really limited and do not show any significant improvement over existing methods.\n\nLIMITATIONS:\nNo potential negative societal impacts", "TITLE": "Official Review", "RECOMMENDATION": 6, "REVIEWER_CONFIDENCE": 4, "SOUNDNESS_CORRECTNESS": 4, "DATE": "2024-07-15"}