The Elements of Differentiable Programming

Chapter 12Differentiating through integration

In this chapter, we study how to differentiate through integrals, with a focus on expectations and solutions of ordinary differential equations.

12.1 Differentiation under the integral sign

Given two Euclidean spaces Θ\Theta and Y\cY, and a function f:Θ×Y→Rf: \Theta \times\cY \rightarrow \RR, we often want to differentiate an integral of the form F(θ)≔∫Yf(θ,y)dy. F(\thetav) \coloneqq \int_\cY f(\thetav, \y)d\y. Provided that we can swap integration and differentiation, we have ∇F(θ)=∫Y∇θf(θ,y)dy. \nabla F(\thetav) = \int_\cY \nabla_\thetav f(\thetav, \y)d\y. The conditions enabling us to do so are best examined in the context of measure theory. We refer the reader to e.g. (Cohn, 2013) for a course on measure theory and Flanders (1973) for an in-depth study of the differentiation under the integral sign. Briefly, if Θ=Y=R\Theta = \cY = \RR, the following conditions are sufficient.

  1. ff is measurable in both its arguments, and f(θ,⋅)f(\theta, \cdot) is integrable for almost all θ∈Θ\theta \in \Theta fixed,

  2. f(⋅,y)f(\cdot, y) is absolutely continuous for almost all y∈Yy \in \cY, that is, there exists an integrable function g(⋅,y)g(\cdot, y) such that f(θ,y)=f(θ0,y)+∫θ0θg(τ,y)dτf(\theta, y) = f(\theta_0, y) + \int_{\theta_0}^\theta g(\tau, y)d\tau,

  3. ∂1f(θ,y)\partial_1 f(\theta, y) (which exists almost everywhere if f(⋅,y)f(\cdot, y) is absolutely continuous), is locally integrable, that is, for any closed interval [θ0,θ1][\theta_0, \theta_1], the integral ∫θ0θ1∫∣∂1f(θ,y)∣dydθ\int_{\theta_0}^{\theta_1} \int |\partial_1 f(\theta, y)| dy d\theta is finite.

Any differentiable function f:Θ×Y→Rf:\Theta \times \cY \rightarrow \RR is absolutely continuous. However, the conditions also hold if ff is just absolutely continuous, that is, if f(⋅,y)f(\cdot, y) is differentiable for almost all yy. This weaker assumption can be used to smooth out differentiable almost-everywhere functions, such as the ReLU, as we study in Section 14.4.

12.2 Differentiating through expectations

A special case of differentiating through integrals is differentiating through expectations. We can distinguish between two cases, depending on whether the parameters θ\thetav we wish to differentiate are involved in the distribution or in the function, whose expectation we compute.

12.2.1 Parameter-independent distributions

We first consider expectations of the form F(θ)≔EY∼p[g(Y,θ)]=∫Yg(y,θ)p(y)dy, F(\thetav) \coloneqq \EE_{Y \sim p}[g(Y, \thetav)] = \int_{\cY} g(\y, \thetav) p(\y) d\y, for a random variable Y∈Y⊆RMY \in \cY \subseteq \RR^M, distributed according to a distribution pp, and a function g ⁣:Y×Θ→Rg \colon \cY \times \Theta \to \R. Importantly, the distribution is independent of the parameters θ\thetav. Under mild conditions recalled in Section 12.1, we can swap differentiation and integration to obtain ∇F(θ)=∇θ∫Yg(y,θ)p(y)dy=∫Y∇θg(y,θ)p(y)dy=EY∼p[∇θg(Y,θ)].\begin{align*} \nabla F(\thetav) &= \nabla_\thetav \int_{\cY} g(\y, \thetav) p(\y) d\y \\ &= \int_{\cY} \nabla_\thetav g(\y, \thetav) p(\y) d\y \\ &= \EE_{Y \sim p}[\nabla_\thetav g(Y, \thetav)]. \end{align*} Generally, the expectation cannot be computed in closed form. However, provided that we can sample from pp, we can define a Monte-Carlo estimator of the value F^N(θ)≔1N∑i=1Ng(Yi,θ) \widehat{F}_N(\thetav) \coloneqq \frac{1}{N}\sum_{i=1}^{N} g(Y_i, \thetav) and of the gradient

∇F^N(θ)=1N∑i=1N∇θg(Yi,θ), \nabla \widehat{F}_N(\thetav) = \frac{1}{N}\sum_{i=1}^{N} \nabla_\thetav g(Y_i, \thetav), for NN i.i.d. samples Y1,…,YNY_1, \ldots, Y_N from pp. These estimators are unbiased, meaning that E[F^N(θ)]=F(θ)\EE[\widehat{F}_N(\thetav)] = F(\thetav) and E[∇F^N(θ)]=∇F(θ)\EE[\nabla \widehat{F}_N(\thetav)] = \nabla F(\thetav), and they converge to the true quantity as N→+∞N \rightarrow +\infty. This suggests a simple implementation in an autodiff framework of the approximation of ∇F(θ)\nabla F(\thetav):

  1. Sample y1,…,yNy_1, \ldots, y_N from pp.

  2. Compute F^N(θ)=1N∑i=1Ng(yi,θ)\widehat{F}_N(\thetav) = \frac{1}{N}\sum_{i=1}^{N} g(y_i, \thetav).

  3. Compute the gradient ∇F^N(θ)\nabla \widehat{F}_N(\thetav) by automatic differentiation.

Computing higher-order derivatives follows the same principle: to get an approximation of ∇2F(θ)\nabla^2 F(\thetav), we can simply compute ∇2F^N(θ)\nabla^2 \widehat{F}_N(\thetav) by autodiff. As such, the implementation delineated above is akin to the “discretize-then-optimize” approach used to differentiate through the solution of an ODE (Section 12.6): we implement an approximation of the objective and simply call autodiff on it.

12.2.2 Parameter-dependent distributions

A more challenging case arises when the distribution depends on the parameters θ\thetav: E(θ)≔EY∼pθ[g(Y)]=∫Yg(y)pθ(y)dy, E(\thetav) \coloneqq \EE_{Y \sim p_\thetav}[g(Y)] = \int_{\cY} g(\y) p_\thetav(\y) d\y, where Y∈Y⊆RMY \in \cY \subseteq \RR^M is a random variable, distributed according to a distribution pθp_\thetav parameterized by θ∈Θ\thetav \in \Theta and where g ⁣:Y→Rg \colon \cY \to \R is, depending on the setting, potentially a blackbox function (i.e., we do not have access to its gradients). Typically, θ∈Θ\thetav \in \Theta could be parameters we wish to estimate, or it could indirectly be generated by θ=f(x,w)∈Θ\thetav = f(\x, \w) \in \Theta, where ff is a neural network with parameters w∈W\w \in \cW we wish to estimate. The main difficulty in computing ∇E(θ)\nabla E(\thetav) stems from the fact that θ\thetav are the parameters of the distribution pθp_\thetav. Estimating an expectation E(θ)=EY∼pθ[g(Y)]E(\thetav) = \EE_{Y \sim p_\thetav}[g(Y)] using Monte-Carlo estimation requires us to sample from pθp_\thetav. However, it is not clear how to differentiate EE w.r.t. θ\thetav if θ\thetav is involved in the sampling process.

Continuous case

When Y\cY is a continuous set (that is, pθ(y)p_\thetav(\y) is a probability density function), we can rewrite E(θ)E(\thetav) as E(θ)=∫Ypθ(y)g(y)dy. E(\thetav) = \int_{\cY} p_\thetav(\y) g(\y) d\y. Provided that we can swap integration and differentiation (see Section 12.1), we then have ∇E(θ)=∇θ∫Ypθ(y)g(y)dy=∫Y∇θpθ(y)g(y)dy.\begin{align*} \nabla E(\thetav) &= \nabla_\thetav \int_{\cY} p_\thetav(\y) g(\y) d\y \\ &= \int_{\cY} \nabla_\thetav p_\thetav(\y) g(\y) d\y. \end{align*} Unfortunately, this integral is not an expectation and it could be intractable in general.

Discrete case

When Y\cY is a discrete set (that is, pθ(y)p_\thetav(\y) is a probability mass function), we can rewrite E(θ)E(\thetav) as E(θ)=∑y∈Ypθ(y)g(y). E(\thetav) = \sum_{\y \in \cY} p_\thetav(\y) g(\y). We then obtain ∇E(θ)=∑y∈Yg(y)∇θpθ(y). \nabla E(\thetav) = \sum_{\y \in \cY} g(\y) \nabla_{\thetav} p_\thetav(\y). Again, ∇E(θ)\nabla E(\thetav) is not an expectation. We therefore cannot use Monte-Carlo estimation to estimate the gradient. Instead, we can compute it by brute force, i.e., by summing over all possible y∈Y\y \in \cY. However, this is clearly only computationally tractable if ∣Y∣|\cY| is small or if pθp_\thetav is designed to have sparse support, i.e., so that the set {y∈Y ⁣:pθ(y)≠0}\{\y \in \cY \colon p_\thetav(\y) \neq 0\} is small. Moreover, even if these conditions hold, summing over y\y could be problematic if g(y)g(\y) is expensive to compute. Therefore, exact gradients are seldom used in practice.

In Sections 12.3 and 12.4, we review the score function and pathwise gradient estimators, to (approximately) compute ∇E(θ)\nabla E(\thetav), allowing us to optimize θ\thetav (or w\w using the chain rule) by gradient-based algorithms.

12.2.3 Application to expected loss functions

Differentiating through expectations is particularly useful when working with expected loss functions of the form L(θ;y)≔EY^∼pθ[ℓ(Y^,y)], L(\thetav; \y) \coloneqq \EE_{\hat Y \sim p_\thetav}[\ell(\hat Y, \y)], where y\y is some ground truth. Equivalently, we can set ℓ=−r\ell = -r, where rr is a reward function. As we shall see, the score function estimator will support a discrete loss function ℓ ⁣:Y×Y→R\ell \colon \cY \times \cY \to \R, while the pathwise gradient estimator will require a differentiable loss function ℓ ⁣:RM×Y→R\ell \colon \RR^M \times \cY \to \R. Intuitively, L(θ;y)L(\thetav; \y) will be low if pθp_\thetav assigns high probability to predictions y^\widehat \y with low loss value ℓ(y^,y)\ell(\widehat \y, \y).

In the classification setting, where Y=[M]\cY = [M], pθp_\thetav is often chosen to be the Gibbs distribution, which is a categorical distribution induced by a softargmax pθ(y)≔exp⁡(θy)∑i∈[M]exp⁡(θi)=[softmax(θ)]y∈(0,1), p_\thetav(y) \coloneqq \frac{\exp(\theta_{y})}{\sum_{i \in [M]} \exp(\theta_i)} = \left[\mathrm{softmax}(\thetav)\right]_{y} \in (0, 1), where θy≔f(x,y,w)∈R\theta_{y} \coloneqq f(\x, y, \w) \in \RR are logits produced by a neural network ff. More generally, in the structured prediction setting, where Y⊆RM\cY \subseteq \R^M but ∣Y∣≫M|\cY| \gg M, we often use the distribution pθ(y)≔exp⁡(⟨ϕ(y),θ⟩)∑y′∈Yexp⁡(⟨ϕ(y′),θ⟩), p_\thetav(\y) \coloneqq \frac{\exp(\langle \phi(\y), \thetav \rangle)}{\sum_{\y' \in \cY} \exp(\langle \phi(\y'), \thetav \rangle)}, where θ=f(x,w)∈RM\thetav = f(\x, \w) \in \RR^M.

Given a distribution ρ\rho over X×Y\cX \times \cY, we then want to minimize the expected loss function, also known as risk, R(w)≔E(X,Y)∼ρ[L(f(X,w);Y)]. R(\w) \coloneqq \EE_{(X,Y) \sim \rho}[L(f(X, \w); Y)]. Typically, minimizing R(w)R(\w) is done through some form of gradient descent, which requires us to be able to compute ∇R(w)=E(X,Y)∼ρ[∇wL(f(X,w);Y)]=E(X,Y)∼ρ[∂2f(X,w)∗∇L(f(X,w);Y)]. \begin{aligned} \nabla R(\w) &= \EE_{(X, Y) \sim \rho}[\nabla_\w L(f(X, \w); Y)] \\ &= \EE_{(X, Y) \sim \rho}[\partial_2 f(X, \w)^* \nabla L(f(X, \w); Y)]. \end{aligned} Computing ∇R(w)\nabla R(\w) therefore boils down to computing the gradient of L(θ;y)L(\thetav; \y), which is the gradient of an expectation.

12.2.4 Application to experimental design

In experimental design, we wish to minimize a function g(λ)g(\lambdav), which we assume costly to evaluate. As an example, evaluating g(λ)g(\lambdav) could require us to run a scientific experiment with parameters λ∈RQ\lambdav \in \RR^Q. As another example, in hyperparameter optimization, evaluating g(λ)g(\lambdav) would require us to run a learning algorithm with hyperparameters λ∈RQ\lambdav \in \RR^Q. Instead of solving the problem arg min⁡λ∈RQg(λ)\argmin_{\lambdav \in \RR^Q} g(\lambdav), we can lift the problem to probability distributions and solve arg min⁡θ∈RME(θ)\argmin_{\thetav \in \RR^M} E(\thetav), where E(θ)=Eλ∼pθ[g(λ)]E(\thetav) = \EE_{\lambdav \sim p_\thetav}[g(\lambdav)]. This requires the probability distribution pθp_\thetav to assign high probability to λ\lambdav values that achieve small g(λ)g(\lambdav) value. Solving this problem by stochastic gradient descent requires us to be able to compute estimates of ∇E(θ)\nabla E(\thetav). This can be done for instance with SFE explained in Section 12.3, which does not require gradients of gg, unlike implicit differentiation explained in Chapter 11. This approach also requires us to choose a distribution pθp_\thetav over λ\lambdav. For continuous hyperparameters, a natural choice would be the normal distribution λ∼Normal(μ,Σ)\lambdav \sim \mathrm{Normal}(\muv, \Sigmav), setting θ=(μ,Σ)\thetav = (\muv, \Sigmav). Once we have obtained θ\thetav by minimizing E(θ)E(\thetav), we need a way to recover λ\lambdav. This can be done for example by choosing the mode of the distribution, i.e., arg max⁡λ∈RQpθ(λ)\argmax_{\lambdav \in \RR^Q} p_\thetav(\lambdav), or the mean of the distribution Eλ∼pθ(λ)[λ]\EE_{\lambdav \sim p_\thetav(\lambdav)}[\lambdav]. Of course, in the case of the normal distribution, they coincide.

12.3 Score function estimators, REINFORCE

12.3.1 Scalar-valued functions

The key idea of the score function estimator (SFE), also known as REINFORCE, is to rewrite ∇E(θ)\nabla E(\thetav) as an expectation. The estimator is based on the logarithmic derivative identity ∇θlog⁡pθ(y)=∇θpθ(y)pθ(y)⟺∇θpθ(y)=pθ(y)∇θlog⁡pθ(y). \nabla_\thetav \log p_\thetav(\y) = \frac{\nabla_\thetav p_\thetav(\y)}{p_\thetav(\y)} \Longleftrightarrow \nabla_\thetav p_\thetav(\y) = p_\thetav(\y) \nabla_\thetav \log p_\thetav(\y). Using this identity, we obtain the following gradient estimator.

Proposition 12.1 (SFE for scalar-valued functions)

Given a family of distributions pθp_\thetav on Y\cY, for θ∈Θ\theta \in \Theta, define E(θ)≔EY∼pθ[g(Y)]=∫Ypθ(y)g(y)dy, E(\thetav) \coloneqq \EE_{Y \sim p_\thetav}[g(Y)] = \int_\cY p_\thetav(\y) g(\y) d\y, where Y∈Y⊆RMY \in \cY \subseteq \R^M and g ⁣:Y→Rg \colon \cY \to \R. Then, ∇E(θ)=EY∼pθ[g(Y)∇θlog⁡pθ(Y)]. \nabla E(\thetav) = \EE_{Y \sim p_\thetav}[g(Y) \nabla_\thetav \log p_\thetav(Y)].

Proof

∇E(θ)=∫Y∇θpθ(y)g(y)dy=∫Ypθ(y)g(y)∇θlog⁡pθ(y)dy=EY∼pθ[g(Y)∇θlog⁡pθ(Y)]. \begin{aligned} \nabla E(\thetav) &= \int_{\cY} \nabla_\thetav p_\thetav(\y) g(\y) d\y \\ &= \int_{\cY} p_\thetav(\y) g(\y) \nabla_\thetav \log p_\thetav(\y) d\y \\ &= \EE_{Y \sim p_\thetav}[g(Y) \nabla_\thetav \log p_\thetav(Y)]. \end{aligned}  ◻

The gradient of the log-PDF w.r.t. θ\thetav, ∇θlog⁡pθ(y)\nabla_\thetav \log p_\thetav(\y), is known as the score function, hence the estimator name. SFE is suitable when two requirements are met: it is easy to sample from pθp_\thetav and the score function is available in closed form. Since the SFE gradient is an expectation, we can use Monte-Carlo estimation to compute an unbiased estimator of ∇E(θ)\nabla E(\thetav): ∇E(θ)≈γ^N(θ)≔1N∑i=1Ng(Yi)∇θlog⁡pθ(Yi),(12.1) \nabla E(\thetav) \approx \widehat{\gammav}_N(\thetav) \coloneqq \frac{1}{N} \sum_{i=1}^N g(Y_i) \nabla_\thetav \log p_\thetav(Y_i), \tag{12.1} where Y1,…,YNY_1, \dots, Y_N are sampled from pθp_\thetav.

Interestingly, the gradient of gg is not needed in this estimator. Therefore, there is no differentiability assumption about gg. This is why SFE is useful when gg is a discrete loss function or more generally a blackbox function.

Example 12.1 (SFE with a language model)

In a language model, the probability of a sentence y=(y1,…,yL)\y = (y_1, \dots, y_L) is typically factored using the chain rule of probability (see Section 10.1) pθ(y)≔pθ(y1)pθ(y2∣y1)…pθ(yL∣y1,…,yL−1), p_\thetav(\y) \coloneqq p_\thetav(y_1) p_\thetav(y_2| y_1) \dots p_\thetav(y_L | y_1, \dots, y_{L-1}), where pθp_\thetav is modeled using a transformer or RNN. Note that the probabilities are normalized by construction, so there is no need for an explicit normalization constant. Thanks to this factorization, it is easy to sample from pθp_\thetav using ancestral sampling (see Section 10.5.3) and the log-probability enjoys the simple expression ∇θlog⁡pθ(y)=∇θlog⁡pθ(y1)+∇θlog⁡pθ(y2∣y1)+…+∇θlog⁡pθ(yL∣y1,…,yL−1).\begin{align*} \nabla_\thetav \log p_\thetav(\y) & = \nabla_\thetav \log p_\thetav(y_1) + \nabla_\thetav \log p_\thetav(y_2| y_1) + \dots \\ & \quad + \nabla_\thetav \log p_\thetav(y_L | y_1, \dots, y_{L-1}). \end{align*} This gradient is easy to compute, since the token-wise distributions pθ(yj∣y1,…,yj−1)p_\thetav(y_j|y_1,\dots,y_{j-1}) are typically defined using a softargmax. We can therefore easily compute ∇E(θ)\nabla E(\thetav) under pθp_\thetav using SFE. This is for instance useful to optimize an expected reward, in order to finetune or align a language model (Ziegler et al., 2019).

Another example when ∇θpθ(y)\nabla_\thetav p_\thetav(\y) is available in closed form is in the context of reinforcement learning, where pθ(y)p_\thetav(\y) is a Markov Decision Process (MDP) and is called the policy. Applying the SFE leads to the (vanilla) policy gradient method (Sutton et al., 1999) and can then be used to compute the gradient of an expected cumulative reward. However, SFE is more problematic when used with the Gibbs distribution, due to the explicit normalization constant.

Example 12.2 (SFE with a Gibbs distribution)

The Gibbs distribution is parameterized, for θ∈RY\thetav \in \RR^\mathcal{Y}, pθ(y)≔exp⁡(θy/γ−A(θ))=exp⁡(θy/γ)/exp⁡(A(θ))\begin{align*} p_\thetav(y) \coloneqq \exp(\theta_y /\gamma - A(\thetav)) = \exp(\theta_y / \gamma) / \exp(A(\thetav)) \end{align*} where we defined the log-partition function A(θ)≔log⁡∑y∈Yexp⁡(θy/γ). A(\thetav) \coloneqq \log \sum_{y \in \cY} \exp(\theta_y / \gamma). A typical parametrization is θy=f(x,y,w)\theta_y = f(\x, y, \w) with ff the output of a network on a sample x\x with parameters w\w. We then have log⁡pθ(y)=θy/γ−A(θ), \log p_\thetav(y) = \theta_y / \gamma - A(\thetav), so that ∇θlog⁡pθ(y)=ey/γ−∇A(θ). \nabla_\thetav \log p_\thetav(y) = \e_y / \gamma - \nabla A(\thetav). We therefore see that ∇θlog⁡pθ(y)\nabla_\thetav \log p_\thetav(y) crucially depends on ∇A(θ)\nabla A(\thetav), the gradient of the log-partition. This gradient is available for some structured sets Y\cY, see e.g. (Mensch and Blondel, 2018), but not in general.

As another example, we apply SFE in Section 14.4 to derive the gradient of perturbed functions.

Differentiating through both the distribution and the function

Suppose both the distribution and the function now depend on θ\thetav. When gg is scalar-valued and differentiable w.r.t. θ\thetav, we want to differentiate E(θ)≔EY∼pθ[g(Y,θ)]. E(\thetav) \coloneqq \EE_{Y \sim p_\thetav} [g(Y, \thetav)]. Using the product rule, we obtain ∇E(θ)=EY∼pθ[g(Y,θ)∇θlog⁡pθ(Y)]+EY∼pθ[∇θg(Y,θ)]. \nabla E(\thetav) = \EE_{Y \sim p_\thetav} [g(Y, \thetav) \nabla_\thetav \log p_\thetav(Y)] + \EE_{Y \sim p_\thetav} [\nabla_\thetav g(Y, \thetav)].

Differentiating through joint distributions

Suppose we now want to differentiate through E(θ)≔EY1∼pθ,Y2∼qθ[g(Y1,Y2)]. E(\thetav) \coloneqq \EE_{Y_1 \sim p_\thetav, Y_2 \sim q_\thetav}[g(Y_1,Y_2)]. The gradient is then given by ∇E(θ)=EY1∼pθ,Y2∼qθ[(∇θlog⁡pθ(Y1)+∇θlog⁡qθ(Y2))g(Y1,Y2)], \nabla E(\thetav) = \EE_{Y_1 \sim p_\thetav, Y_2 \sim q_\thetav}[(\nabla_\thetav \log p_\thetav(Y_1) + \nabla_\thetav \log q_\thetav(Y_2)) g(Y_1,Y_2)], which is easily seen by applying Proposition 12.1 on the joint distribution ρθ≔pθ⋅qθ\rho_\thetav \coloneqq p_\thetav \cdot q_\thetav. The extension to more than two variables is straightforward.

12.3.2 Variance reduction

We discuss in this section various techniques for reducing the variance of estimators of ∇E(θ)\nabla E(\thetav), where E(θ)≔EY∼pθ[g(Y)]E(\thetav) \coloneqq \EE_{Y \sim p_\thetav}[g(Y)].

Bias and variance

Recall the definition of γ^N\widehat{\gammav}_N in Eq. (12.1). SFE is an unbiased estimator, meaning that ∇E(θ)=E[γ^N(θ)], \nabla E(\thetav) = \EE[\widehat{\gammav}_N(\thetav)], where the expectation is taken with respect to the NN samples drawn. Since the gradient is vector-valued, we need to define a scalar-valued notion of variance. We do so by using the squared Euclidean distance in the usual variance definition to define V[γ^N(θ)]≔E[∥γ^N(θ)−∇E(θ)∥22]=E[∥γ^N(θ)∥22]−∥∇E(θ)∥22.\begin{align*} \VV[\widehat{\gammav}_N(\thetav)] &\coloneqq \EE [\|\widehat{\gammav}_N(\thetav) - \nabla E(\thetav)\|_2^2] \\ &= \EE[\|\widehat{\gammav}_N(\thetav)\|_2^2] - \|\nabla E(\thetav)\|^2_2. \end{align*} The variance naturally goes to zero as N→∞N \to \infty.

Baseline

SFE is known to suffer from high variance (Mohamed et al., 2020). This means that this estimator may require us to draw many samples from the distribution pθp_\thetav to work well in practice. One of the simplest variance reduction technique consists in shifting the function gg with a constant β\beta, called a baseline, to obtain ∇E(θ)=EY∼pθ[(g(Y)−β)∇θlog⁡pθ(Y)]. \nabla E(\thetav) = \EE_{Y \sim p_\thetav}[(g(Y) - \beta) \nabla_\thetav \log p_\thetav(Y)]. The reason this is still a valid estimator of ∇E(θ)\nabla E(\thetav) stems from EY∼pθ[∇θlog⁡pθ(Y)]=EY∼pθ[∇θpθ(Y)pθ(Y)]=∇θEY∼pθ[1⁡]=∇θ1⁡=0,\begin{align*} \EE_{Y \sim p_\thetav}[ \nabla_\thetav \log p_\thetav(Y) ] &= \EE_{Y \sim p_\thetav}\left[ \frac{\nabla_\thetav p_\thetav(Y)}{p_\thetav(Y)} \right] \\ &= \nabla_\thetav \EE_{Y \sim p_\thetav}[\ones] \\ &= \nabla_\thetav \ones \\ &= \zeros, \end{align*} for any valid distribution pθp_\thetav. The baseline β\beta is often set to the running average of past values of the function gg, though it is neither optimal nor does it guarantee to lower the variance (Mohamed et al., 2020).

REINFORCE leave-one-out (RLOO)

A simple way to reduce the variance is REINFORCE leave-one-out (RLOO) (Ahmadian et al., 2024; Kool et al., 2019). The key idea is to draw multiple independent samples Y1,…,YNY_1, \dots, Y_N from pθp_\thetav and for each sample YiY_i, to use the remaining samples (Yj)j≠i(Y_j)_{j \neq i} as a baseline. The RLOO gradient estimator is defined as Γ^N(θ)≔1N∑i=1N(g(Yi)−1N−1∑j≠ig(Yj))∇θlog⁡pθ(Yi). \hat{\Gamma}_N(\thetav) \coloneqq \frac{1}{N} \sum_{i=1}^N \big(g(Y_i) - \frac{1}{N-1} \sum_{j \neq i} g(Y_j)\big) \nabla_\thetav \log p_\thetav(Y_i). This is an unbiased estimator, meaning that ∇E(θ)=E[Γ^N(θ)], \nabla E(\thetav) = \EE[\hat{\Gamma}_N(\thetav)], where the expectation is taken over Y1,…,YNY_1, \dots, Y_N. This comes from the independence of Yi,YjY_i, Y_j for i≠ji\neq j, such that E[g(Yj)∇θlog⁡pθ(Yi)]=E[g(Yj)]E[∇θlog⁡pθ(Yi)]=0\EE[g(Y_j) \nabla_\thetav\log p_\thetav(Y_i)] = \EE[g(Y_j)]\EE[\nabla_\thetav\log p_\thetav(Y_i)]= 0 since E[∇θlog⁡pθ(Yi)]=0\EE[\nabla_\thetav\log p_\thetav(Y_i)]= 0 by Bartlett’s first identity (12.2).

It can be checked that the estimator can equivalently be rewritten as Γ^N(θ)=1N−1∑i=1N(g(Yi)−1N∑j=1Ng(Yj))∇θlog⁡pθ(Yi). \hat{\Gamma}_N(\thetav) = \frac{1}{N-1} \sum_{i=1}^N \big(g(Y_i) - \frac{1}{N} \sum_{j=1}^N g(Y_j)\big) \nabla_\thetav \log p_\thetav(Y_i). This is slightly more convenient to implement, as we can use β≔1N∑j=1Ng(Yj)\beta \coloneqq \frac{1}{N} \sum_{j=1}^N g(Y_j) as a shared baseline across samples.

Control variates

Another general technique are control variates. Let us denote the expectation of a function h ⁣:RM→Rh \colon \RR^M \to \RR under the distribution pθp_\thetav as H(θ)≔EY∼pθ[h(Y)]. H(\thetav) \coloneqq \EE_{Y \sim p_\thetav}[h(Y)]. Suppose that H(θ)H(\thetav) and its gradient ∇H(θ)\nabla H(\thetav) are known in closed form. Then, for any γ≥0\gamma \ge 0, we clearly have E(θ)=EY∼pθ[g(Y)]=EY∼pθ[g(Y)−γ(h(Y)−H(θ))]=EY∼pθ[g(Y)−γh(Y)]+γH(θ)\begin{align*} E(\thetav) &= \EE_{Y \sim p_\thetav}[g(Y)] \\ &= \EE_{Y \sim p_\thetav}[g(Y) - \gamma (h(Y) - H(\thetav))] \\ &= \EE_{Y \sim p_\thetav}[g(Y) - \gamma h(Y)] + \gamma H(\thetav) \end{align*} and therefore ∇E(θ)=∇θEY∼pθ[g(Y)−γh(Y)]+γ∇H(θ).\begin{align*} \nabla E(\thetav) &= \nabla_\thetav \EE_{Y \sim p_\thetav}[g(Y) - \gamma h(Y)] + \gamma \nabla H(\thetav). \end{align*} Applying SFE, we then obtain ∇E(θ)=EY∼pθ[(g(Y)−γh(Y))∇θlog⁡pθ(Y)]+γ∇H(θ). \nabla E(\thetav) = \EE_{Y \sim p_\thetav}[(g(Y) - \gamma h(Y)) \nabla_\thetav \log p_\thetav(Y)] + \gamma \nabla H(\thetav). Examples of function hh include a bound on ff or a second-order Taylor expansion of ff, assuming that these approximations are easier to integrate than ff (Mohamed et al., 2020).

12.3.3 Vector-valued functions

It is straightforward to extend the SFE to vector-valued functions.

Proposition 12.2 (SFE for vector-valued functions)

Given a family of distributions pθp_\thetav on Y\cY, for θ∈Θ\theta \in \Theta, define E(θ)≔EY∼pθ[g(Y)]=∫Ypθ(y)g(y)dy, E(\thetav) \coloneqq \EE_{Y \sim p_\thetav}[g(Y)] = \int_\cY p_\thetav(\y) g(\y) d\y, where Y∈YY \in \cY, g ⁣:Y→Gg \colon \cY \to \cG. The JVP of EE at θ∈Θ\thetav\in \Theta along v∈Θ\v\in \Theta is ∂E(θ)v=EY∼pθ[⟨∇θlog⁡pθ(Y),v⟩g(Y)]∈G \partial E(\thetav) \v = \EE_{Y \sim p_\thetav}[\langle \nabla_\thetav \log p_\thetav(Y), \v \rangle g(Y)] \in \cG and the VJP of EE at θ∈Θ\thetav\in \Theta along u∈G\u \in \cG is ∂E(θ)∗u=EY∼pθ[∇θlog⁡pθ(Y)⟨u,g(Y)⟩]∈Θ. \partial E(\thetav)^* \u = \EE_{Y \sim p_\thetav}[\nabla_\thetav \log p_\thetav(Y) \langle\u, g(Y) \rangle] \in \Theta. The Jacobian of EE at θ∈Θ\thetav \in \Theta can then be written as ∂E(θ)=EY∼pθ[g(Y)⊗∇θlog⁡pθ(Y)], \jac E(\thetav) = \EE_{Y \sim p_\thetav}[g(Y) \otimes \nabla_\thetav \log p_\thetav(Y)], where ⊗\otimes denotes the outer product.

Proof

The VJP of EE at θ∈Θ\thetav \in \Theta along u∈G\u \in \cG amounts to computing the gradient of the scalar function ⟨E(θ),u⟩=EY∼pθ[⟨g(Y),u⟩] \langle E(\thetav), \u\rangle = \EE_{Y \sim p_\thetav}[\langle g(Y), \u\rangle] The expression of the VJP follows by using the SFE on the scalar valued integrand ⟨g(Y),u⟩\langle g(Y), \u\rangle. The JVP is obtained as the adjoint operator of the VJP and the Jacobian follows. ◻

Differentiating through both the distribution and the function

If θ\thetav now influences both the distribution and the function, E(θ)≔EY∼pθ[g(Y,θ)], E(\thetav) \coloneqq \EE_{Y \sim p_\thetav} [g(Y, \thetav)], then, we obtain ∂E(θ)=EY∼pθ[g(Y,θ)⊗∇θlog⁡pθ(Y)]+EY∼pθ[∂θg(Y,θ)]. \partial E(\thetav) = \EE_{Y \sim p_\thetav} [g(Y, \thetav) \otimes \nabla_\thetav \log p_\thetav(Y)] + \EE_{Y \sim p_\thetav} [\partial_\thetav g(Y, \thetav)].

12.3.4 Second derivatives

Using the previous subsection with g(y,θ)=g(y)∇θlog⁡pθ(θ)g(\y, \thetav) = g(\y) \nabla_\thetav \log p_\thetav(\thetav), we easily obtain an estimator of the Hessian.

Proposition 12.3 (SFE for the Hessian)

Let us define the scalar-valued function E(θ)≔EY∼pθ[g(Y)]E(\thetav) \coloneqq \EE_{Y \sim p_\thetav}[g(Y)]. Then, ∇2E(θ)=EY∼pθ[g(Y)∇θlog⁡pθ(Y)⊗∇θlog⁡pθ(Y)]+EY∼pθ[g(Y)∇θ2log⁡pθ(Y)].\begin{align*} \nabla^2 E(\thetav) =& \EE_{Y \sim p_\thetav} [g(Y) \nabla_\thetav \log p_\thetav(Y) \otimes \nabla_\thetav \log p_\thetav(Y)] + \\ &\EE_{Y \sim p_\thetav} [g(Y) \nabla^2_\thetav \log p_\thetav(Y)]. \end{align*}

This can also be derived using the second-order log-derivative ∇θ2log⁡pθ(y)=1pθ(y)∇θ2pθ(y)−1pθ(y)2∇θpθ(y)⊗∇θpθ(y) \nabla^2_\thetav \log p_\thetav(\y) = \frac{1}{p_\thetav(\y)} \nabla^2_\thetav p_\thetav(\y) - \frac{1}{p_\thetav(\y)^2} \nabla_\thetav p_\thetav(\y) \otimes \nabla_\thetav p_\thetav(\y) so that ∇θ2pθ(y)=pθ(y)[∇θ2log⁡pθ(y)+∇θlog⁡pθ(y)⊗∇θlog⁡pθ(y)]. \nabla^2_\thetav p_\thetav(\y) = p_\thetav(\y) \left[ \nabla^2_\thetav \log p_\thetav(\y) + \nabla_\thetav \log p_\thetav(\y) \otimes \nabla_\thetav \log p_\thetav(\y) \right].

The Bartlett identities are expressions relating the moments of the score function (gradient of the log-likelihood function). Using Proposition 12.1 with g(y)=1g(\y) = 1 and ∫Ypθ(y)dy=1\int_\cY p_\thetav(\y) d\y = 1, we obtain EY∼pθ[∇θlog⁡pθ(Y)]=0,(12.2) \EE_{Y \sim p_\thetav}[\nabla_\thetav \log p_\thetav(Y)] = \zeros, \tag{12.2} which is known as Bartlett’s first identity. Similarly, using Proposition 12.3, we obtain EY∼pθ[∇θ2log⁡pθ(Y)]+EY∼pθ[∇θlog⁡pθ(Y)⊗∇θlog⁡pθ(Y)]=EY∼pθ[∇θ2log⁡pθ(Y)]+cov[log⁡pθ(Y)]=0,(12.3) \begin{aligned} &\EE_{Y \sim p_\thetav} [\nabla^2_\thetav \log p_\thetav(Y)] + \EE_{Y \sim p_\thetav} [\nabla_\thetav \log p_\thetav(Y) \otimes \nabla_\thetav \log p_\thetav(Y)] \\ =& \EE_{Y \sim p_\thetav} [\nabla^2_\thetav \log p_\thetav(Y)] + \mathrm{cov}[\log p_\thetav(Y)] \\ =& \zeros, \end{aligned} \tag{12.3} which is known as Bartlett’s second identity.

12.3.5 Autodiff-friendly implementation

So far, we derived expressions of score function estimators for first and second derivatives. From a user perspective, instead of manually implementing these expressions, it would be more convenient if we could just call autodiff on some function and recover the correct expressions of the score function estimators. This can be achieved using the so-called magicbox operator (Foerster et al., 2018). This operator is defined as M(τ)≔exp⁡(τ−S(τ)), \cM(\tau) \coloneqq \exp(\tau - \cS(\tau)), where S\cS is the stop gradient operator.

During the evaluation of a program, the stop gradient operator acts as the identity. During automatic differentiation, that is, during forward or reverse mode autodiff, this operator stops any flow of derivatives. In other words, its Jacobian is zero on any inputs despite evaluating as the identity. Such an operator does not exist mathematically, but it can be defined in an autodiff framework using custom derivation rules. Evaluations and derivatives of programs making S\cS intervene are then to be understood first in terms of the autodiff framework and its custom rules.

Coming back to the magicbox operator, its evaluation and its derivatives in an autodiff framework are then for any τ∈R\tau \in \cR M(τ)=exp⁡(τ−τ)=1M′(τ)=(τ−S(τ))′M(τ)=1⋅1=1M′′(τ)=⋯=1\begin{align*} \cM(\tau) & = \exp(\tau - \tau) = 1\\ \cM'(\tau) & = (\tau - \cS(\tau))' \cM(\tau) = 1 \cdot 1 = 1\\ \cM''(\tau) & = \dots = 1 \end{align*} The “magic” happens when we compose the magicbox operator with another function. Consider a (twice) differentiable function f ⁣:RM→Rf \colon \RR^M \to \RR. We then have (M∘f)(θ)=1∇(M∘f)(θ)=M′(f(θ))∇f(θ)=∇f(θ)∇2(M∘f)(θ)=M′′(f(θ))∇f(θ)⊗∇f(θ)+M′(f(θ))∇2f(θ)=∇f(θ)⊗∇f(θ)+∇2f(θ).\begin{align*} (\cM \circ f)(\thetav) &= 1 \\ \nabla (\cM \circ f)(\thetav) &= \cM'(f(\thetav))\nabla f(\thetav) = \nabla f(\thetav) \\ \nabla^2 (\cM \circ f)(\thetav) &= \cM''(f(\thetav)) \nabla f(\thetav) \otimes \nabla f(\thetav) + \cM'(f(\thetav)) \nabla^2 f(\thetav) \\ &= \nabla f(\thetav) \otimes \nabla f(\thetav) + \nabla^2 f(\thetav). \end{align*} Let YY be a sample from pθp_\thetav and let us define f(θ)≔log⁡pθ(Y)f(\thetav) \coloneqq \log p_\thetav(Y). Then, (M∘f)(θ)=1∇(M∘f)(θ)=∇θlog⁡pθ(Y)∇2(M∘f)(θ)=∇θlog⁡pθ(Y)⊗∇θlog⁡pθ(Y)+∇θ2log⁡pθ(Y),\begin{align*} (\cM \circ f)(\thetav) &= 1 \\ \nabla (\cM \circ f)(\thetav) &= \nabla_\thetav \log p_\thetav(Y) \\ \nabla^2 (\cM \circ f)(\thetav) &= \nabla_\thetav \log p_\thetav(Y) \otimes \nabla_\thetav \log p_\thetav(Y) + \nabla^2_\thetav \log p_\thetav(Y), \end{align*} correctly recovering the expressions for the first derivative in Proposition 12.1 and for the second derivative in Proposition 12.3. Let us define the functions E(θ)≔EY∼pθ[g(Y)]Eˉ(θ)≔EY∼S(pθ)[g(Y)M(log⁡pθ(Y))].\begin{align*} E(\thetav) &\coloneqq \EE_{Y \sim p_\thetav}[g(Y)] \\ \bar{E}(\thetav) &\coloneqq \EE_{Y \sim \cS(p_\thetav)}[g(Y) \cM(\log p_\thetav(Y))]. \end{align*} We then correctly obtain for all θ∈RM\thetav \in \RR^M E(θ)=Eˉ(θ)∇E(θ)=∇Eˉ(θ)∇2E(θ)=∇2Eˉ(θ).\begin{align*} E(\thetav) &= \bar{E}(\thetav) \\ \nabla E(\thetav) &= \nabla \bar{E}(\thetav) \\ \nabla^2 E(\thetav) &= \nabla^2 \bar{E}(\thetav). \end{align*} The key benefit is that Eˉ\bar{E} is compatible with autodiff frameworks, while EE is not. In practice, we can draw NN samples Y1,…,YNY_1, \dots, Y_N (without differentiating through the sampling) and define EˉN(θ)≔1N∑i=1Ng(Yi)M(log⁡pθ(Yi)). \bar{E}_N(\thetav) \coloneqq \frac{1}{N} \sum_{i=1}^N g(Y_i) \cM(\log p_\thetav(Y_i)). By Monte-Carlo estimation, we then have E(θ)=E[EˉN(θ)]∇E(θ)=E[∇EˉN(θ)]∇2E(θ)=E[∇2EˉN(θ)],\begin{align*} E(\thetav) &= \EE[\bar{E}_N(\thetav)] \\ \nabla E(\thetav) &= \EE[\nabla \bar{E}_N(\thetav)] \\ \nabla^2 E(\thetav) &= \EE[\nabla^2 \bar{E}_N(\thetav)], \end{align*} where the expectation is taken over Y1,…,YNY_1, \dots, Y_N.

12.4 Path gradient estimators, reparametrization trick

As we saw previously, the main difficulty in computing gradients of expectations arises when the parameters θ\thetav play a role in the distribution pθp_\thetav being sampled. The key idea of path gradient estimators (PGE), also known as reparametrization trick, is to rewrite the expectation in such a way that the parameters are moved from the distribution to the function, using a change of variable.

12.4.1 Location-scale transforms

The canonical example of path gradient estimator is differentiating through the expectation E(μ,σ)≔EU∼Normal(μ,σ2)[g(U)], E(\mu, \sigma) \coloneqq \EE_{U \sim \mathrm{Normal}(\mu, \sigma^2)}[g(U)], where g ⁣:R→Rg \colon \RR \to \RR is a differentiable function. If we let Z∼Normal(0,1)Z \sim \mathrm{Normal}(0, 1), it is easy to check that U=μ+σZU = \mu + \sigma Z. We can therefore write E(μ,σ)=EZ∼Normal(0,1)[g(μ+σZ)]. E(\mu, \sigma) = \EE_{Z \sim \mathrm{Normal}(0, 1)}[g(\mu + \sigma Z)]. The key advantage is that we can now easily compute the derivatives by mere application of the chain rule, since the parameters μ\mu and σ\sigma are moved from the distribution to the function: ∂∂μE(μ,σ)=EZ∼Normal(0,1)[g′(μ+σZ)]∂∂σE(μ,σ)=EZ∼Normal(0,1)[Z⋅g′(μ+σZ)].\begin{align*} \frac{\partial}{\partial \mu} E(\mu, \sigma) &= \EE_{Z \sim \mathrm{Normal}(0, 1)}[g'(\mu + \sigma Z)] \\ \frac{\partial}{\partial \sigma} E(\mu, \sigma) &= \EE_{Z \sim \mathrm{Normal}(0, 1)}[Z \cdot g'(\mu + \sigma Z)]. \end{align*} The change of variable U≔μ+σZ(12.4) U \coloneqq \mu + \sigma Z \tag{12.4} is called a location-scale transform. Such a transformation exists, not only for the normal distribution, but for location-scale family distributions, i.e., distributions parametrized by a location parameter μ\mu and a scale parameter σ>0\sigma > 0, such that UU is distributed according to a distribution in the same family as ZZ is distributed. Besides the normal distribution, examples of location-scale family distributions include the Cauchy distribution, the uniform distribution, the logistic distribution, the Laplace distribution, and Student’s tt-distribution.

We can easily relate the cumulative distribution function (CDF) and the probability density function (PDF) of ZZ to that of UU, and vice-versa.

Proposition 12.4 (CDF and PDF of location-scale family distributions)

Let FZ(z)≔P(Z≤z)F_Z(z) \coloneqq \PP(Z \le z) and fZ(z)≔FZ′(z)f_Z(z) \coloneqq F_Z'(z). If U≔μ+σZU \coloneqq \mu + \sigma Z, then FZ(z)=FU(μ+σz)  ⟺  FU(u)=FZ(u−μσ)fZ(z)=σfU(μ+σz)  ⟺  fU(u)=1σfZ(u−μσ).\begin{align*} F_Z(z) &= F_U(\mu + \sigma z) \iff F_U(u) = F_Z\left(\frac{u - \mu}{\sigma}\right) \\ f_Z(z) &= \sigma f_U(\mu + \sigma z) \iff f_U(u) = \frac{1}{\sigma} f_Z\left(\frac{u - \mu}{\sigma}\right). \end{align*}

Proof

We have FZ(z)=P(Z≤z)=P(U−μσ≤z)=P(U≤μ+σz)=FU(μ+σz)\begin{align*} F_Z(z) &= \PP(Z \le z) \\ &= \PP\left(\frac{U-\mu}{\sigma} \le z\right) \\ &= \PP(U \le \mu + \sigma z) \\ &= F_U(\mu + \sigma z) \end{align*} and we obtain fZ(z)f_Z(z) by differentiating FZ(z)F_Z(z). ◻

12.4.2 Differentiable transforms

We can generalize the idea of path gradient estimator (PGE) to any change of variable U≔T(Z,θ), U \coloneqq T(Z, \thetav), where T ⁣:RM×RQ→RMT \colon \RR^M \times \RR^Q \to \RR^M is a differentiable transformation. For example, if we gather μ\mu and σ\sigma as θ≔(μ,σ)\thetav \coloneqq (\mu, \sigma), we can write the location-scale transform as U=T(Z,θ)=μ+σZ. U = T(Z, \thetav) = \mu + \sigma Z. We can derive the path gradient estimator for any such differentiable transformation TT.

Proposition 12.5 (Path gradient estimator)

Let us define E(θ)≔EU∼pθ[g(U)], E(\thetav) \coloneqq \EE_{U \sim p_\thetav}[g(U)], where U∈U⊆RMU \in \cU \subseteq \RR^M and g ⁣:RM→Rg \colon \RR^M \to \RR is differentiable. Suppose there is a differentiable transformation T ⁣:RM×RQ→RMT \colon \R^M \times \R^Q \to \R^M such that if Z∼pZ \sim p (where pp does not depend on θ\thetav) and U≔T(Z,θ)U \coloneqq T(Z, \thetav), then U∼pθU \sim p_\thetav. Then, we have E(θ)=EZ∼p[h(Z,θ)]=EZ∼p[g(T(Z,θ))], E(\thetav) = \EE_{Z \sim p}[h(Z, \thetav)] = \EE_{Z \sim p}[g(T(Z, \thetav))], where h(z,θ)≔g(T(z,θ))h(\z, \thetav) \coloneqq g(T(\z, \thetav)). This implies ∇E(θ)=EZ∼p[∇2h(Z,θ)]=EZ∼p[∂2T(Z,θ)∗∇g(T(Z,θ))]. \begin{aligned} \nabla E(\thetav) &= \EE_{Z \sim p}[\nabla_2 h(Z, \thetav)] \\ &= \EE_{Z \sim p}[\partial_2 T(Z, \thetav)^* \nabla g(T(Z, \thetav))]. \end{aligned}

The path gradient estimator (a.k.a. reparametrization trick) gives an unbiased estimator of ∇E(θ)\nabla E(\thetav). It has however two key disadvantages. First, it assumes that gg is differentiable (almost everywhere), which may not always be the case. Second, it assumes that gg is well-defined on RM\R^M, not on U\cU, which could be problematic for some discrete loss functions, such as the zero-one loss function or ranking loss functions.

As an example of differentiable transform, in machine learning, we can sample Gaussian noise ZZ and make it go through a neural network with parameters w\w to generate an image X≔T(Z,w)X \coloneqq T(Z, \w). In statistics, many distributions are related to each other through differentiable transforms, as we recall below.

Example 12.3 (Some differentiable transforms in statistics)

We give below a non-exhaustive list of differentiable transform examples.

  • If X∼Normal(μ,σ2)X \sim \mathrm{Normal}(\mu, \sigma^2), then exp⁡(X)∼Lognormal(μ,σ2)\exp(X) \sim \mathrm{Lognormal}(\mu, \sigma^2).

  • If U∼Uniform(0,1)U \sim \mathrm{Uniform}(0,1), then −log⁡(U)/λ∼Exponential(λ)-\log(U) / \lambda \sim \mathrm{Exponential}(\lambda).

  • If X1,…,XN∼Exponential(λ)X_1,\dots,X_N \sim \mathrm{Exponential}(\lambda) (i.i.d.), then ∑i=1NXi∼Gamma(N,λ)\sum_{i=1}^N X_i \sim \mathrm{Gamma}(N, \lambda).

  • If Xi∼Gamma(αi,θ)X_i \sim \mathrm{Gamma}(\alpha_i,\theta) for i∈[K]i \in [K], then (X1∑i=1KXi,…,XK∑i=1KXi)∼Dirichlet(α1,…,αK)\left( \frac{X_1}{\sum_{i=1}^K X_i}, \dots, \frac{X_K}{\sum_{i=1}^K X_i} \right) \sim \mathrm{Dirichlet}(\alpha_1,\dots,\alpha_K).

12.4.3 Inverse transforms

The inverse transform method can be used for sampling from a probability distribution, given access to its associated quantile function. Recall that the cumulative distribution function (CDF) associated with a random variable YY is the function FY ⁣:R→[0,1]F_Y \colon \RR \to [0,1] defined by FY(y)≔P(Y≤y). F_Y(y) \coloneqq \PP(Y \le y). The quantile function is then a function QY ⁣:[0,1]→RQ_Y \colon [0,1] \to \RR such that QY(π)=yQ_Y(\pi) = y for π=FY(y)\pi = F_Y(y). Assuming FYF_Y is continuous and strictly increasing, we have that QYQ_Y is the inverse CDF, QY(π)=FY−1(π). Q_Y(\pi) = F^{-1}_Y(\pi). In the general case of CDF functions that are not strictly increasing, the quantile function is usually defined as QY(π)≔inf⁡{y∈R ⁣:π≤FY(y)}. Q_Y(\pi) \coloneqq \inf \{y \in \RR \colon \pi \le F_Y(y) \}. Given access to the quantile function QY(π)Q_Y(\pi) associated with a distribution pp, inverse transform sampling allows us to sample from pp by first drawing a sample from the uniform distribution and then making this sample go through the quantile function.

Proposition 12.6 (Inverse transform sampling)

Suppose Y∼pY \sim p,
where pp is a distribution with quantile function QYQ_Y. If U∼Uniform(0,1)U \sim \text{Uniform}(0,1), then QY(U)∼pQ_Y(U) \sim p.

Proof

If π≤FY(t)\pi \leq F_Y(t), then by definition of QYQ_Y, QY(π)≤tQ_Y(\pi) \leq t. If π≥FY(t)\pi \geq F_Y(t), then by definition of QYQ_Y, FY(QY(π))≥πF_Y(Q_Y(\pi)) \geq \pi, so FY(QY(π))≥FY(t)F_Y(Q_Y(\pi)) \geq F_Y(t) and since a CDF is always non-decreasing, QY(π)≥tQ_Y(\pi) \geq t. Hence, we have, QY(π)≤t  ⟺  π≤FY(t)Q_Y(\pi) \leq t \iff \pi \leq F_Y(t), so P(QY(U)≤t)=P(U≤FY(t))=FY(t).\begin{align*} \PP(Q_Y(U)\leq t) & = \PP(U \leq F_Y(t)) \\ & = F_Y(t). \end{align*} The CDFs of QY(U)Q_Y(U) and YY coincide, hence they have the same distribution. ◻

If the quantile function is differentiable, we can therefore use it as a transformation within the reparametrization trick. Indeed, if Y∼pθY \sim p_\thetav, where pθp_\thetav is a distribution with parameter θ\thetav and quantile function QY(π,θ)Q_Y(\pi, \thetav), then we have E(θ)=EY∼pθ[g(Y)]=Eπ∼Uniform(0,1)[g(QY(π,θ))] E(\thetav) = \EE_{Y \sim p_\thetav}[g(Y)] = \EE_{\pi \sim \text{Uniform}(0,1)}[g(Q_Y(\pi, \thetav))] and therefore, by the reparametrization trick (Proposition 12.5), ∇E(θ)=Eπ∼Uniform(0,1)[∂2QY(π,θ)∗∇g(QY(π,θ))]. \nabla E(\thetav) = \EE_{\pi \sim \text{Uniform}(0,1)}[ \partial_2 Q_Y(\pi, \thetav)^* \nabla g(Q_Y(\pi, \thetav)) ].

Example 12.4 (Examples of quantile functions)

If
Y∼Exponential(λ)Y \sim \text{Exponential}(\lambda), the CDF of YY is π=FY(y)=1−exp⁡(−λy)\pi = F_Y(y) = 1 - \exp(-\lambda y) for y≥0y \ge 0 and therefore the quantile function is QY(π,λ)=−log⁡(1−π)λQ_Y(\pi, \lambda) = -\frac{\log(1-\pi)}{\lambda}. If Y∼Normal(μ,σ2)Y \sim \text{Normal}(\mu, \sigma^2), the CDF is FY(y)=12[1+erf(y−μσ2)]F_Y(y) = \frac{1}{2}\left[1 + \text{erf}\left(\frac{y - \mu}{\sigma\sqrt{2}}\right)\right] and the quantile function is QY(π,θ)=μ+σ2⋅erf−1(2π−1)Q_Y(\pi, \thetav) = \mu + \sigma \sqrt{2} \cdot \mathrm{erf}^{-1}(2\pi - 1), where θ=(μ,σ)\thetav = (\mu, \sigma). This therefore defines an alternative transformation to the location-scale transformation in Eq. (12.4).

Note that, in the above example, the error function erf\mathrm{erf} and its inverse do not enjoy analytical expressions but autodiff packages usually provide numerical routines to compute them and differentiate through them. Nonetheless, one caveat of the inverse transform is that it indeed requires access to (approximations of) the quantile function and its derivatives, which may be difficult for complicated distributions.

12.4.4 Pushforward operators

Pushforward distributions

We saw so far that the reparametrization trick is based on using a change of variables in order to differentiate an expectation w.r.t. the parameters of the distribution. In this section, we further formalize that approach using pushforward distributions.

Definition 12.1 (Pushforward distribution)

Suppose Z∼pZ \sim p, where pp is a distribution over Z\cZ. Given a continuous map T ⁣:Z→UT \colon \cZ \to \cU, the pushforward distribution of pp through TT is the distribution qq according to which U≔T(Z)∈UU \coloneqq T(Z) \in \cU is distributed, i.e., U∼qU \sim q.

Although not explicit in the above, the transformation TT can depend on some learnable parameters, for example if TT is a neural network. Intuitively, the pushforward distribution is obtained by moving the position of all the points in the support of pp. We give a few examples below.

A crucial aspect of the pushforward distribution qq is that it can be implicitly defined, meaning that we do not necessarily need to know the explicit form of the associated PDF. In fact, it is easy to sample from qq, provided that it is easy to sample from pp: U∼q  ⟺  Z∼p,U≔T(Z).\begin{align*} U \sim q \iff Z \sim p, U &\coloneqq T(Z). \end{align*} Hence the usefulness of the pushforward distribution in generative modeling. Furthermore, if pp has associated PDF pZp_Z, we can compute the expectation of a function ff according to qq as EU∼q[f(U)]=EZ∼p[f(T(Z))]=∫Zf(T(z))pZ(z)dz,\begin{align*} \EE_{U \sim q}[f(U)] = \EE_{Z \sim p}[f(T(Z))] = \int_{\cZ} f(T(\z)) p_Z(\z) d\z, \end{align*} even though we do not know the explicit form of the PDF of qq.

Pushforward measures

More generally, we can define the notion of pushforward, in the language of measures. Denote M(Z)\cM(\cZ) the set of measures on a set Z\cZ. A measure α∈M(Z)\alpha \in \cM(\cZ), that has a density dα(z)≔pZ(z)dzd\alpha(\z) \coloneqq p_Z(\z) d\z, can be integrated against a function ff as ∫Zf(z)dα(z)=∫Zf(z)pZ(z)dz. \int_\cZ f(\z) d\alpha(\z) = \int_\cZ f(\z) p_Z(\z) d\z. A measure α\alpha is called a probability measure if it is positive and satisfies α(Z)=∫Zdα(z)=∫ZpZ(z)dz=1\alpha(\cZ) = \int_\cZ d\alpha(\z) = \int_\cZ p_Z(\z) d\z = 1. See Peyré and Cuturi (2019, 2) for a concise introduction.

Definition 12.2 (Pushforward operator and measure)

Given a continuous map T ⁣:Z→UT \colon \cZ \to \cU and some measure α∈M(Z)\alpha \in \cM(\cZ), the pushforward measure β=T♯α∈M(U)\beta = T_\sharp \alpha \in \cM(\cU) is such that for all continuous functions f∈C(U)f \in \cC(\cU) ∫Uf(u)dβ(u)=∫Zf(T(z))dα(z). \int_\cU f(\u) d\beta(\u) = \int_\cZ f(T(\z)) d\alpha(\z). Equivalently, for any measurable set A⊂U\cA \subset \cU, we have β(A)=α({z∈Z ⁣:T(z)∈A})=α(T−1(A)), \beta(\cA) = \alpha(\{\z \in \cZ \colon T(\z) \in \cA\}) = \alpha(T^{-1}(\cA)), where T−1(A)={z∈Z:T(z)∈A}T^{-1}(\cA) = \{\z \in \cZ: T(\z)\in \cA\}.

Importantly, the pushforward operator preserves positivity and mass, therefore if α\alpha is a probability measure, then so is T♯αT_\sharp \alpha. The pushforward of a probability measure therefore defines a pushforward distribution (since a distribution can be parametrized by a probability measure).

12.4.5 Change-of-variables theorem

We saw that a pushforward distribution associated with a variable UU is implicitly defined through a transform U≔T(Z)U \coloneqq T(Z) and can be easily sampled from as long as it is easy to sample ZZ. However, in some applications (e.g., density estimation), we may want to know the PDF associated with UU. Assuming the transform TT is invertible, we have Z=T−1(U)Z = T^{-1}(U) and therefore for A⊆U\cA \subseteq \cU, we have P(U∈A)=P(Z∈T−1(A))=∫T−1(A)pZ(z)dz.\begin{align*} \PP(U \in \cA) = \PP(Z \in T^{-1}(\cA)) = \int_{T^{-1}(\cA)} p_Z(\z) d\z. \end{align*} Using the change-of-variables theorem from multivariate calculus, assuming T−1T^{-1} is available, we can give an explicit formula for the PDF of the pushforward distribution, see e.g. (Schwartz, 1954; Taylor, 2002).

Proposition 12.7 (PDF of the pushforward distribution)

Suppose
Z∼pZ \sim p, where pp is a distribution over Z\cZ, with PDF pZp_Z. Given a diffeomorphism T ⁣:Z→UT \colon \cZ \to \cU (i.e., an invertible and differentiable map), the pushforward distribution of pp through TT is the distribution qq such that U≔T(Z)∼qU \coloneqq T(Z) \sim q and its PDF is qU(u)=∣det⁡(∂T−1(u))∣pZ(T−1(u)), q_U(\u) = |\det(\partial T^{-1}(\u))| p_Z(T^{-1}(\u)), where ∂T−1(u)\partial T^{-1}(\u) is the Jacobian of T−1 ⁣:U→ZT^{-1} \colon \cU \to \cZ.

Using this formula, we obtain P(U∈A)=∫ApU(u)du=∫A∣det⁡(∂T−1(u))∣pZ(T−1(u))du.\begin{align*} \PP(U \in \cA) &= \int_{\cA} p_U(\u) d\u \\ &= \int_{\cA} |\det(\partial T^{-1}(\u))| p_Z(T^{-1}(\u)) d\u. \end{align*} Using the inverse function theorem (Theorem 11.7), we then have ∂T−1(u)=(∂T(T−1(u)))−1, \partial T^{-1}(\u) = (\partial T(T^{-1}(\u)))^{-1}, under the assumption that T(z)T(\z) is continuously differentiable and has invertible Jacobian ∂T(z)\partial T(\z). Normalizing flows are parametrized transformations TT designed such that T−1T^{-1} and its Jacobian ∂T−1\partial T^{-1} are easy to compute; see e.g. Kobyzev et al. (2019; Papamakarios et al., 2021) for a review.

12.5 Stochastic programs

A stochastic program is a program that involves some form of randomness. In a stochastic program, the final output, as well as intermediate variables, may therefore be random variables. In other words, a stochastic program induces a probability distribution over program outputs, as well as over execution trajectories.

12.5.1 Stochastic computation graphs

A stochastic program can be represented by a stochastic computation graph as originally introduced by Schulman et al. (2015). Departing from that work, our exposition explicitly supports two types of intermediate operations: sampling from a conditional distribution or evaluating a function. These operations can produce either deterministic variables or random variables.

Function and distribution nodes

Formally, we define a stochastic computation graph as a directed acyclic graph G=(V,E)\cG = (\cV, \cE), where V=Vf∪Vp\cV = \cV_f \cup \cV_p, Vf\cV_f is the set of function nodes and Vp\cV_p is the set of distribution nodes. Similarly to computation graphs reviewed in Section 4.1.3, we number the nodes as V={0,1,…,K}\cV =\{0, 1, \ldots, K\}. Node 00 corresponds to the input s0∈S0\s_0 \in \cS_0, which we assume to be deterministic. It is the variable with respect to which we wish to differentiate. Node KK corresponds to the program output SK∈SKS_K \in \cS_K, which we assume to be a random variable. A node k∈{1,…,K}k \in \{1,\dots,K\} can either be a function node k∈Vfk \in \cV_f with an associated function fkf_k or a distribution node k∈Vpk \in \cV_p, with associated conditional distribution pkp_k. A stochastic program has at least one distribution node, the source of randomness. Otherwise, it is a deterministic program. As for computation graphs, the set of edges E\cE is used to represent dependencies between nodes. We denote the parents of node kk by pa⁡(k)\parent(k).

Deterministic and random variables

We distinguish between two types of intermediate variables: deterministic variables sk\s_k and random variables SkS_k. Therefore, a distribution pkp_k or a function fkf_k may receive both types of variables as conditioning or input. It is then convenient to split pa⁡(k)\parent(k) as pa⁡(k)=determ⁡(k)∪random⁡(k)\parent(k)= \dparent(k) \cup \rparent(k), where we defined the deterministic parents determ⁡(k)≔{i1,…,ipk}\dparent(k) \coloneqq \{i_1, \ldots, i_{p_k}\} and the random parents random⁡(k)≔{j1,…,jqk}\rparent(k) \coloneqq \{j_1, \ldots, j_{q_k}\}. Therefore, si1,…,sipk\s_{i_1}, \ldots, \s_{i_{p_k}} are the deterministic parent variables and Sj1,…,SjqkS_{j_1}, \ldots, S_{j_{q_k}} are the random parent variables, of node kk.

Executing a stochastic program

We assume that nodes 0,1,…,K0, 1, \dots, K are in topological order (if this is not the case, we need to perform a topological sort). Given parent variables si1,…,sipk\s_{i_1}, \ldots, \s_{i_{p_k}} and Sj1,…,SjqkS_{j_1}, \ldots, S_{j_{q_k}}, a node k∈{1,…,K}k \in \{1, \dots, K\} produces an output as follows.

Unless the associated conditional distribution pkp_k is a delta distribution, that puts all the probability mass on a single point, the output of a distribution node k∈Vpk \in \cV_p is necessarily a random variable Sk∈SkS_k \in \cS_k. For function nodes k∈Vfk \in \cV_f, the output of the function fkf_k is a random variable Sk∈SkS_k \in \cS_k if at least one of the parents of kk produces a random variable. Otherwise, if all parents of kk produce deterministic variables, the output of fkf_k is a deterministic variable sk∈Sk\s_k \in \cS_k.

The entire procedure is summarized in Algorithm 12.1. We emphasize that SK=f(s0)∈SKS_K = f(\s_0) \in \cS_K is a random variable. Therefore, a stochastic program (implicitly) induces a distribution over SKS_K, and also over intermediate random variables SkS_k. Executing the stochastic program allows us to draw samples from that distribution.

Algorithm 12.1: Executing a stochastic program

Nodes: 1,…,K1,\dots,K in topological order, where node kk is either a function fkf_k or a conditional distribution pkp_k

Input: input s0∈S0\s_0 \in \cS_0

for k≔1,…,Kk \coloneqq 1, \ldots, K do

Retrieve pa⁡(k)=determ⁡(k)∪random⁡(k)\parent(k) = \dparent(k) \cup \rparent(k)

if k∈Vpk \in \cV_p then ▷  Distribution node

Sk∼pk(⋅∣sdeterm⁡(k),Srandom⁡(k))S_k \sim p_k(\cdot|\s_{\dparent(k)},S_{\rparent(k)})

else if k∈Vfk \in \cV_f then ▷  Function node

if ∣random⁡(k)∣≠0|\rparent(k)| \neq 0 then

Sk≔fk(sdeterm⁡(k),Srandom⁡(k))S_k \coloneqq f_k(\s_{\dparent(k)}, S_{\rparent(k)}) ▷  Output is a R.V.

else if ∣random⁡(k)∣=0|\rparent(k)| = 0 then

sk≔fk(sdeterm⁡(k))\s_k \coloneqq f_k(\s_{\dparent(k)}) ▷  Output is deterministic

Output: f(s0)≔SK∈SKf(\s_0) \coloneqq S_K \in \cS_K

Special cases

If all nodes are function nodes, we recover computation graphs, reviewed in Section 4.1.3. If all nodes are distribution nodes, we recover Bayesian networks, reviewed in Section 10.5.

12.5.2 Examples

We now present several examples that illustrate our formalism. We use the legend below in the following illustrations.

As can be seen, the gradient expressions can quickly become quite complicated, demonstrating the merits of automatic differentiation in stochastic computation graphs.

12.5.3 Unbiased gradient estimators

The output of a stochastic program is a random variable SK≔f(s0). S_K \coloneqq f(\s_0). It implicitly defines a probability distribution p(⋅∣s0)p(\cdot|\s_0) such that SK∼p(⋅∣s0)S_K \sim p(\cdot|\s_0). Executing the stochastic program once gives us an i.i.d. sample from p(⋅∣s0)p(\cdot|\s_0).

Since derivatives are defined for deterministic variables, we need a way to convert a random variable to a deterministic variable. One way to do so is to consider the expected value (another way would be the mode) E(s0)≔E[SK]=E[f(s0)]∈conv⁡(SK), E(\s_0) \coloneqq \EE[S_K] = \EE[f(\s_0)] \in \conv(\cS_K), where the expectation is over SK∼p(⋅∣s0)S_K \sim p(\cdot|\s_0) or equivalently over the intermediate random variables SkS_k Sk∼pk(⋅∣sdeterm⁡(k),Srandom⁡(k)), S_k \sim p_k(\cdot|\s_{\dparent(k)}, S_{\rparent(k)}), for k∈Vpk \in \cV_p (the distribution nodes). We then wish to compute the gradient or more generally the Jacobian of E(s0)E(\s_0).

If all nodes in the stochastic computation graph are function nodes, we can estimate the gradient of E(s0)E(\s_0) using the pathwise estimator a.k.a.  reparametrization trick (Section 12.4). This is the approach taken by Kingma and Welling (2013) and Rezende et al. (2014).

If all nodes in the stochastic computation graph are distribution nodes, we can use the SFE estimator (Section 12.3). Schulman et al. (2015) propose a surrogate loss so that using autodiff on that loss produces an unbiased gradient of the expectation, using the SFE estimator. Foerster et al. (2018) extend the approach to support high-order differentiation. Krieken et al. (2021) further extend the approach by supporting different estimators per node, as well as control variates.

Converting distribution nodes into function nodes and vice-versa

Our formalism uses two types of nodes: distribution nodes with associated conditional distribution pkp_k and function nodes with associated function fkf_k. It is often possible to convert between node types.

Converting a distribution node into a function node is exactly the reparametrization trick studied in Section 12.4. We can use transformations such as the location-scale transform or the inverse transform.

Converting a function node into a distribution node can be done using the change-of-variables theorem, studied in Section 12.4.5, on a pushforward distribution.

Because the pathwise estimator has lower variance than SFE, this is the method of choice when the fkf_k functions are available. The conversion from distribution node to function node and vice-versa is illustrated in Fig. 12.1.

Figure 12.1: It is sometimes possible to convert a distribution node to a function node and vice-versa using a suitable transformation.

12.5.4 Local vs. global expectations

A stochastic computation graph can be seen as a stochastic process, a collection of random variables SkS_k, indexed by kk, the position in the topological order. However, random variables are incompatible with autodiff. Replacing random variables by their expectation can be seen as a way to make them compatible with autodiff. Two strategies are then possible.

As we saw in the previous section, a strategy is to consider the expectation of the last output SKS_K. This strategy corresponds to a global smoothing. The two major advantages are that i) we do not need to assume that fk+1f_{k+1} is well-defined on conv⁡(Sk)\conv(\cS_k) and ii) this induces a probability distribution over program executions. This is for instance useful to compute the variance of the program. The gradient of the program’s expected value can be estimated by the reparametrization trick or by the SFE, depending on the type of nodes used.

A second strategy is to replace an intermediate random variable Sk∈SkS_k \in \cS_k, for k∈{1,…,K}k \in \{1, \dots, K\}, by its expectation E[Sk]∈conv⁡(Sk)\EE[S_k] \in \conv(\cS_k). This strategy corresponds to a local smoothing. A potential drawback of this approach is that E[Sk]\EE[S_k] belongs to conv⁡(Sk)\conv(\cS_k), the convex hull of Sk\cS_k. Therefore, the function fk+1f_{k+1} in which E[Sk]\EE[S_k] is fed must be well-defined on conv⁡(Sk)\conv(\cS_k), which may not always be the case. In the case of control flows, another disadvantage is computational. We saw in Section 5.6 and Section 5.7 that using a soft comparison operator within a conditional statement induces a distribution on a binary or categorical random variable, corresponding to the branch to be selected. A conditional statement can then be locally smoothed out by replacing the random variable by its expectation i.e., a convex combination of all the branches. This means that, unless the distribution has sparse support, all branches must be evaluated.

12.6 Differential equations

12.6.1 Parameterized differential equations

From residual networks to neural ODEs

Starting from s0≔x\s_0 \coloneqq \x, residual networks, reviewed in Section 4.6, iterate for k∈{1,…,K}k \in \{1, \dots,K\} sk≔sk−1+hk(sk−1,wk). \s_k \coloneqq \s_{k-1} + h_k(\s_{k-1}, \w_k). A residual network can be seen as parameterizing incremental discrete-time input changes (hence the name “residual”) sk−sk−1=hk(sk−1,wk). \s_k - \s_{k-1} = h_k(\s_{k-1}, \w_k). Chen et al. (2018) proposed to parameterize continuous-time (instantaneous) changes instead. They considered the evolution s(t)\s(t) of the inputs in continuous time driven by a function h(t,s,w)h(t, \s, \w) parameterized by w\w, starting from x\x. Formally, the evolution s(t)\s(t) is the solution of the ordinary differential equation (ODE) s(0)=xs′(t)=h(t,s(t),w)t∈[0,T]\begin{align*} \s(0) &= \x \\ \s'(t) &= h(t, \s(t), \w) \quad t \in [0, T] \tag{12.5}\end{align*} Here, s′(t)\s'(t) is the vector of derivatives of s\s as defined in Remark 2.4, and TT denotes a final time for the trajectory. The output of such a neural ODE (Chen et al., 2018) is then f(x,w)≔s(T)f(\x, \w) \coloneqq \s(T). Alternatively, the output can be seen as the solution of an integration problem f(x,w)=s(T)=x+∫0Th(t,s(t),w)dt.(12.6) f(\x, \w) = \s(T) = \x + \int_0^T h(t, \s(t), \w)dt. \tag{12.6} Differential equations like Eq. (12.5) arise in many contexts beyond neural ODEs, ranging from modeling physical systems to pandemics (Braun and Golubitsky, 1983). Moreover, the differential equation presented in Eq. (12.5) is just an example of an ordinary differential equation, while controlled differential equations or stochastic differential equations can also be considered.

Existence of a solution

First and foremost, the question is whether s(t)\s(t) is well-defined. Fortunately, the answer is positive under mild conditions, as shown by Picard-Lindelöf’s theorem recalled below (Butcher, 2016, Theorem 16).

Theorem 12.1 (Existence and uniqueness of ODE solutions)

If h:[0,T]×S→Sh: [0, T] \times \cS \rightarrow \cS is continuous in its first variable and Lipschitz-continuous in its second variable, then there exists a unique differentiable map s:[0,T]→S\s: [0, T] \rightarrow \cS satisfying s(0)=s0s′(t)=h(t,s(t))t∈[0,T],\begin{align*} \s(0) &= \s_0 \\ \s'(t) &= h(t, \s(t)) \quad t \in [0, T], \end{align*} for some given s0∈S\s_0 \in \cS.

For time-independent linear functions h(t,s)=Ash(t, \s) =\A\s, the integral in Eq. (12.6) can be computed in closed form as st=exp⁡(tA)(s0), \s_t = \exp(t\A)(\s_0), where exp⁡(A)\exp(\A) is the matrix exponential. Hence, the output s(T)\s(T) can be expressed as a simple function of the parameters (A\A in this case). However, generally, we do not have access to such analytical solutions, and, just as for solving optimization problems in Chapter 11, we need to resort to some iterative algorithms.

Integration methods

To numerically solve an ODE, we can use integration methods, whose goal is to build a sequence sk\s_k that approximates the solution s(t)\s(t) at times tkt_k. The simplest integration method is the explicit Euler method, which approximates the solutions between times tk−1t_{k-1} and tkt_k as s(tk−1)−s(tk)=∫tk−1tkh(t,s(t),w)dt≈δkh(tk−1,s(tk−1),w),\begin{align*} \s(t_{k-1}) - \s(t_k) & = \int_{t_{k-1}}^{t_k} h(t, \s(t), \w)dt \\ & \approx \delta_k h(t_{k-1}, \s(t_{k-1}), \w), \end{align*} for a time-step δk≔tk−tk−1. \delta_k \coloneqq t_k - t_{k-1}. The resulting integration scheme consists in computing starting from s0=x\s_0 = \x, for k∈{1,…,K}k \in \{1, \ldots, K\}, sk≔sk−1+δkh(tk−1,sk−1,w). \s_k \coloneqq \s_{k-1} + \delta_k h(t_{k-1}, \s_{k-1}, \w). Assimilating δkh(tk−1,sk−1,w)\delta_k h(t_{k-1}, \s_{k-1}, \w) with hk(sk−1,wk)h_k(\s_{k-1}, \w_k), we find that residual networks are essentially the discretization of a neural ODE by an explicit Euler method; more precisely, a non-autonomous neural ODE, see e.g. (Davis et al., 2020).

Euler’s forward method is only one integration method among many. To cite a few, there are implicit Euler methods, semi-implicit methods, Runge-Kutta methods, linear multistep methods, etc. See, e.g., Gautschi (2011) for a detailed review. The quality of an integration method is measured by its consistency and its stability (Gautschi, 2011). These concepts naturally influence the development of evaluation and differentiation techniques for ODEs. We briefly summarize them below.

Given a fixed time interval δk=δ\delta_k = \delta and K=⌈T/δ⌉K = \lceil T/\delta\rceil points, an integration method is consistent of order kk if ∥sk−s(kδ)∥=O(δk)\|\s_k - \s(k \delta)\| = O(\delta^k) as δ→0\delta\rightarrow 0 and therefore k→+∞k\rightarrow +\infty. The higher the order kk, the fewer points we need to reach an approximation error ε\varepsilon on the points considered. The term ∥sk−s(kδ)∥=O(δk)\|\s_k - \s(k \delta)\| = O(\delta^k) is reminiscent of the error encountered in finite differences (Chapter 7) and is called the truncation error.

The (absolute) stability of a method is defined by the set of time-steps such that the integration method can integrate s′(t)=λs(t)s'(t) = \lambda s(t) for some λ∈C\lambda \in \CC without blowing up as t→+∞t\rightarrow +\infty.

12.6.2 Continuous adjoint method

Since different parameters w\w induce different trajectories associated with h(t,s,w)h(t, \s, \w) in Eq. (12.5), we may want to select one of these trajectories by minimizing some criterion. For example, we may consider selecting w∈W\w \in \cW by minimizing a loss LL on the final point of the trajectory, min⁡w∈WL(f(x,w),y),(12.7) \min_{\w\in \cW} L(f(\x, \w), \y), \tag{12.7} where f(x,w)≔s(T)=x+∫0Th(t,s(t),w)dt. f(\x, \w) \coloneqq \s(T) = \x + \int_0^T h(t, \s(t), \w)dt. To solve such problems, we need to access gradients of LL composed with ff through VJPs of the solution of the ODE. The VJPs can actually be characterized as solutions of an ODE themselves thanks to the continuous time adjoint method (Pontryagin, 1985), presented below, and whose proof is postponed to Section 12.6.6.

Proposition 12.8 (Continuous-time adjoint method)

Consider a function h:[0,T]×S×W→Sh: [0, T] \times \cS \times \cW \rightarrow \cS, continuous in its first variable, Lipschitz-continuous and continuously differentiable in its second variable. Assume that ∂3h(t,s,w)\partial_3 h(t, \s, \w) exists for any t,s,wt, \s, \w, and is also continuous in its first variable, Lipschitz-continuous in its second variable. Denote s:[0,T]→S\s:[0,T] \rightarrow \cS the solution of the ODE s(0)=xs′(t)=h(t,s(t),w)t∈[0,T],\begin{align*} \s(0) &= \x \\ \s'(t) &= h(t, \s(t), \w) \quad t \in [0, T], \end{align*} and f(x,w)=s(T)f(\x, \w) = \s(T) the final state of the ODE at time TT.

Then, the function ff is differentiable, and for an output direction u∈S\u \in \cS, its VJP along u\u is given by ∂f(x,w)∗u=(r(0),g) \partial f(\x, \w)^*\u = (\r(0), \g) for g=∫0T∂3h(t,s(t),w)∗r(t)dt \g = \int_{0}^{T} \partial_3 h(t, \s(t), \w)^* \r(t) dt and for r\r solving the adjoint (backward) ODE r′(t)=−∂2h(t,s(t),w)∗r(t)r(T)=u.\begin{align*} \r'(t) & = - \partial_2 h(t, \s(t), \w)^* \r(t) \\ \r(T) &= \u . \end{align*} In particular, the gradient ∇(L∘f)(x,w)\nabla (L \circ f)(\x, \w) for L:S→RL: \cS \rightarrow \RR a differentiable loss is obtained by solving the adjoint ODE with r(T)=∇L(s(T))\r(T) = \nabla L(\s(T)).

Example 12.5 (Fitting data through the solution of an ODE)

As an illustrative example, we can consider optimizing the parameters of an ODE to fit some data points. Namely, we may seek a continuous time solution z(t;w)\z(t; \w) of a modified Lotka Volterra ODE z′(t;w)=(αz1(t;w)−βz1(t;w)z2(t;w)−γz2(t;w)+δz1(t;w)z2(t;w))+c, \z'(t; \w) = \begin{pmatrix} \alpha z_1(t;\w) - \beta z_1(t;\w) z_2(t;\w) \\ -\gamma z_2(t;\w) + \delta z_1(t;\w) z_2(t;\w) \end{pmatrix} + \c, for w=(α,β,γ,δ,c)\w = (\alpha, \beta, \gamma, \delta, \c), that fits some observations z1,…,zT\z_1, \ldots, \z_T. The optimization problem then consists of min⁡w∑j=1T∥z(tj;w)−zj∥2, \min_{\w}\sum_{j=1}^{T} \|\z(t_j;\w) - \z_j\|^2, and requires backpropagating through the solution z(⋅;w)\z(\cdot;\w) of the ODE w.r.t. its candidate parameters w\w. Fig. 12.2 illustrates such a problem with varying candidate parameters.

Figure 12.2: Finding the optimal parameters of an ODE to fit some observed data. The dots represent the trajectories of a dynamical system observed at regular times (time is represented here by a gradient color, the lighter the color, the larger the time). Each line represents the solution of an ODE given by some hyperparameters w\w. The objective is to find the hyperparameters of the ODE such that its solution fits the data points. Green and orange lines fail to do so while the blue line fits the data. To compute such parameters w\w, we need to backpropagate through the solution of the ODE.

12.6.3 Gradients via the continuous adjoint method

Proposition 12.8 gives a formal definition of the gradient. However, just as computing the mapping f(x,w)f(\x, \w) itself, computing its VJP or the gradient of L∘fL\circ f requires solving an integration problem. Note that the integration of r(t)\r(t) in Proposition 12.8 requires also values of s(t)\s(t). Therefore, we need to integrate both r(t)\r(t) and s(t)\s(t). Such an approach is generally referred to as optimize-then-discretize because we first formulate the gradient in continuous time (the “optimize part”) and then discretize the resulting ODE.

Simple discretization scheme

A first approach consists in defining a backward discretization scheme that can approximate s(t)\s(t) backward in time. Namely, by defining σ(t)=s(T−t),ρ(t)=r(T−t)\sigmav(t)= \s(T-t), \rhov(t) = \r(T-t), and γ(t)=∫tT∂3h(τ,s(τ),w)∗r(τ)dτ\gammav(t) = \int_t^T \partial_3 h(\tau, \s(\tau), \w)^*\r(\tau) d\tau, the derivative of L∘fL\circ f is given by (ρ(T),γ(T))(\rhov(T), \gammav(T)). The functions σ,ρ,γ\sigmav, \rhov, \gammav are solutions of a standard ODE σ(0)=s(T),σ′(t)=−h(T−t,σ(t),w),ρ(0)=∇L(s(T)),ρ′(t)=∂2h(T−t,σ(t),w)∗ρ(t),γ(0)=0,γ′(t)=∂3h(T−t,σ(t),w)∗ρ(t).\begin{align*} \sigmav(0) & = \s(T), \hspace*{30pt} \sigmav'(t) = -h(T-t, \sigmav(t), \w), \\ \rhov(0) & = \nabla L(\s(T)), \hspace*{6pt} \rhov'(t) = \partial_2 h(T-t, \sigmav(t), \w)^* \rhov(t), \\ \gammav(0) & = 0, \hspace*{48pt} \gammav'(t) = \partial_3 h(T-t, \sigmav(t), \w)^*\rhov(t). \end{align*} The above ODE can then be solved by any integration method. Note, however, that it requires first computing s(T)\s(T) and ∇L(s(T))\nabla L(\s(T)) by an integration method. The overall computation of the gradient using an explicit Euler method to solve forward and backward ODEs is summarized in Algorithm 12.2.

Algorithm 12.2: Gradient computation via continuous adjoint method with Euler explicit discretization

Functions: h:[0,T]×S×W→Rh: [0, T] \times \cS \times \cW \rightarrow \RR, L:S→RL: \cS \rightarrow \RR

Inputs: input x\x, parameters w\w, number of discretization steps KK.

Set discretization step δ=T/K\delta = T/K, denote hk(s,w)=h(kδ,s,w)h_k(\s, \w) = h(k\delta, \s, \w).

Set s0≔x\s_0 \coloneqq \x

for k≔1,…,Kk \coloneqq 1, \ldots, K do ▷  Forward discretization

Compute sk≔sk−1+δhk−1(sk−1,w)\s_k \coloneqq \s_{k-1} + \delta h_{k-1}(\s_{k-1}, \w).

Compute u≔∇L(sK)\u \coloneqq \nabla L(\s_K).

Initialize rK≔u\r_K \coloneqq \u, s^K=sK\hat \s_K = \s_K, gK=0\g_K= \zeros

for k≔K,…,1k \coloneqq K, \ldots, 1 do ▷  Backward discretization

Compute s^k−1≔s^k−δhk(s^k,w)\hat \s_{k-1} \coloneqq \hat \s_k - \delta h_k(\hat \s_k, \w)

Compute rk−1≔rk+δ∂2hk(s^k,w)∗rk\r_{k-1} \coloneqq \r_k + \delta \partial_2 h_k(\hat \s_k, \w)^* \r_k

Compute gk−1≔gk+δ∂3hk(s^k,w)∗rk\g_{k-1} \coloneqq \g_k + \delta \partial_3 h_k(\hat \s_k, \w)^*\r_k

Output: (r0,g0)≈∇(L∘f)(x,w)(\r_0, \g_0) \approx \nabla (L\circ f)(\x, \w)

Algorithm 12.2 naturally looks like the reverse mode of autodiff for a residual neural network with shared weights. A striking difference is that the intermediate computations sk\s_k are not kept in memory and, instead, new variables s^k\hat \s_k are computed along the backward ODE. One may believe that by switching to continuous time, we solved the memory issues encountered in reverse-mode autodiff. Unfortunately, this comes at the cost of numerical stability. As we use a discretization scheme to recompute the intermediate states backward in time through s^k\hat \s_k in Algorithm 12.2, we accumulate some truncation errors.

To understand the issue here, consider applying Algorithm 12.2 repeatedly on the same parameters but using s^0\hat \s_0 instead of s0=x\s_0=\x each time. In the continuous realm, σ(T)=s(0)\sigmav(T) = \s(0). But after discretization, s^0≈σ(T)\hat \s_0 \approx \sigmav(T) does not match s0\s_0. Therefore, by applying Algorithm 12.2 with s0=s^0\s_0= \hat \s_0, we would not get the same output even if in continuous time we naturally should have. This phenomenon is illustrated in Fig. 12.3. It intuitively shows why Algorithm 12.2 induces some noise in the estimation of the gradient.

Figure 12.3: Forward and backward discretizations when using the continuous adjoint method.

Multiple shooting scheme

An alternative approach consists in integrating both the forward and backward ODEs jointly. Namely, we may solve an ODE with boundary values s′(t)=h(t,s(t),w),s(0)=x,r′(t)=−∂2h(t,s(t),w)∗r(t),r(T)=∇L(s(T))g′(t)=−∂3h(t,s(t),w)∗r(t),g(T)=0,\begin{align*} \s'(t) & = h(t, \s(t), \w), \quad \s(0) = \x, \\ \r'(t) & = - \partial_2 h(t, \s(t), \w)^* \r(t), \quad \r(T) = \nabla L(\s(T)) \\ \g'(t) & = - \partial_3 h(t, \s(t), \w)^*\r(t), \quad \g(T) = 0, \end{align*} by means of a multiple shooting method or a collocation method (Stoer et al., 1980). This approach still requires ∇L(s(T))\nabla L(\s(T)) to be approximated first.

12.6.4 Gradients via reverse-mode on discretization

A simpler approach consists in replacing the objective in Eq. (12.7) by its version discretized using some numerical method, such as an Euler forward discretization scheme. That is, we seek to solve min⁡w∈WL(sK)wheresk=sk−1+δh(kδ,sk−1,w) k∈{1,…,K}, \min_{\w \in \cW} \quad L(\s_K) \quad \text{where} \quad \s_k = \s_{k-1} + \delta h(k\delta, \s_{k-1}, \w) ~ k \in \{1, \ldots, K\}, with s0=0\s_0 = \zeros and δ\delta some discretization step. Gradients of the objective can be computed by automatic differentiation. That approach is often referred to as discretize-then-optimize. At first glance, this approach may suffer from very high memory requirements. Indeed, to get an accurate solution of the ODE, a numerical integration method may require KK to be very large. Since a naive implementation of reverse-mode automatic differentiation has a memory that scales linearly with KK, computing the gradient by a discretize-then-optimize method could be prohibitive. However, the memory requirements may easily be amortized using checkpointing, as explained in Section 8.5; see also (Gholaminejad et al., 2019).

As for the optimize-then-discretize method, we still accumulate some truncation errors in the forward discretization process. This discretization error occurs when computing the gradient in reverse-mode too. The discretize-then-optimize method can be seen as computing gradients of a surrogate objective. For that objective, the gradients are correct and well-defined. However, they may not match the gradients of the true ODE formulation.

To compare the discretize-then-optimize and optimize-then-discretize approaches, Gholaminejad et al. (2019) compared their performance on an ODE whose solution can be computed analytically by selecting hh to be linear in s\s. The authors observed that discretize-then-optimize generally outperformed optimize-then-discretize. A middle ground can actually be found by using reversible differentiation schemes.

12.6.5 Reversible discretization schemes

Our exposition of the optimize-then-discretize or discretize-then-optimize approaches used a simple Euler explicit discretization scheme. However, for both approaches, we could have used other discretization schemes instead, such as reversible discretization schemes.

A reversible discretization scheme is a discretization scheme such that we have access to a closed-form formula for the inverse of its discretization step. Formally, a discretization method M\cM builds an approximation (sk)k=1K(\s_k)_{k=1}^{K} of the solution of an ODE s′(t)=h(t,s(t))\s'(t) = h(t, \s(t)) on an interval [0,T][0, T] by computing for k∈(1,…,K)k \in (1,\dots, K) tk,sk,ck=M(tk−1,sk−1,ck−1;h,δ),\begin{align*} t_k, \s_k, \c_k = \cM(t_{k-1}, \s_{k-1}, \c_{k-1}; h, \delta), \tag{12.8}\end{align*} where δ>0\delta>0 is some fixed discretization step, tkt_k is the time step (typically tk=tk−1+δt_k = t_{k-1} + \delta), sk\s_k is the approximation of s(tk)\s(t_k), and ck\c_k is some additional context variable used by the discretization method to build the iterates. An explicit Euler method does not have a context, but just as an optimization method may update some internal states, a discretization method can update some context variable. The discretization scheme in Eq. (12.8) is a forward discretization scheme as we took a positive discretization step. By taking a negative discretization step, we obtain the corresponding backward discretization scheme, for k∈(K,…,1)k \in (K, \dots, 1), tk−1,sk−1,ck−1=M(tk,sk,ck;h,−δ).\begin{align*} t_{k-1}, \s_{k-1}, \c_{k-1} = \cM(t_k, \s_k, \c_k; h, -\delta). \end{align*} A discretization method is reversible if we have access to M−1\cM^{-1} to recompute the inputs of the discretization step from its outputs, tk−1,sk−1,ck=M−1(tk,sk,ck;h,δ). t_{k-1}, \s_{k-1}, \c_k = \cM^{-1}(t_k, \s_k, \c_k; h, \delta). A reversible discretization method is symmetric if the backward discretization scheme is exactly the inverse of the forward discretization scheme, i.e., M(tk,sk,ck;h,−δ)=M−1(tk,sk,ck;h,δ).\begin{align*} \cM(t_k, \s_k, \c_k; h, -\delta) = \cM^{-1}(t_k, \s_k, \c_k; h, \delta). \end{align*} The explicit Euler method is clearly not symmetric and a priori not reversible, unless we can solve for yk−1\y_{k-1}, the equation yk=yk−1+δf(yk−1)\y_k = \y_{k-1} + \delta f(\y_{k-1}).

Leapfrog method

The (asynchronous) leapfrog method (Mutze, 2013; Zhuang et al., 2021) on the other hand is an example of symmetric reversible discretization method. For a constant discretization step δ\delta, given tk−1,sk−1,ck−1t_{k-1}, \s_{k-1}, \c_{k-1} and a function hh, it computes tˉk−1≔tk−1+δ2sˉk−1≔sk−1+δ2ck−1cˉk−1≔h(tˉk−1,sˉk−1)tk≔tˉk−1+δ2sk≔sˉk−1+δ2cˉk−1ck≔2cˉk−1−ck−1M(tk−1,sk−1,ck−1;h,δ)≔(tk,sk,ck).\begin{align*} \bar t_{k-1} & \coloneqq t_{k-1} + \frac{\delta}{2} \\ \bar \s_{k-1} & \coloneqq \s_{k-1} + \frac{\delta}{2} \c_{k-1} \\ \bar \c_{k-1} & \coloneqq h(\bar t_{k-1}, \bar \s_{k-1}) \\ t_k & \coloneqq \bar t_{k-1} + \frac{\delta}{2} \\ \s_k & \coloneqq \bar \s_{k-1} + \frac{\delta}{2} \bar \c_{k-1} \\ \c_k & \coloneqq 2 \bar \c_{k-1} - \c_{k-1} \\ \mathcal{M}(t_{k-1}, \s_{k-1}, \c_{k-1}; h, \delta) & \coloneqq (t_k, \s_k, \c_k). \hspace*{60pt} \end{align*} One can verify that we indeed have M(tk,sk,ck;h,−δ)=(tk−1,sk,ck)\mathcal{M}(t_k, \s_k, \c_k; h, -\delta) = (t_{k-1}, \s_k, \c_k).

By using a reversible symmetric discretization scheme in the optimize-then-discretize approach, we ensure that, at the end of the backward discretization pass, we recover exactly the original input. Therefore, by repeating forward and backward discretization schemes we always get the same gradient, which was not the case for an Euler explicit scheme.

By using a reversible discretization scheme in the discretize-then-optimize method, we address the memory issues of reverse mode autodiff. As explained in Section 8.6, we can recompute intermediate values during the backward pass rather than storing them.

Momentum residual networks

In the leapfrog method, the additional variables ck\c_k may actually be interpreted as velocities of a system whose acceleration is driven by the given function, that is, s′′(t)=h(t,s(t),w)\s''(t) = h(t, \s(t), \w). Such an interpretation suggests alternatives to the usual neural ODE paradigm. For instance, momentum neural networks (Sander et al., 2021b), can be interpreted as the discretization of a second-order ordinary differential equation, which is naturally amenable to reversible differentiation schemes with a low memory footprint.

12.6.6 Proof of the continuous adjoint method

In the following, we denote s(t,x,w)\s(t, \x, \w) the solution of the ODE at time tt given the input x\x and the parameters w\w. We focus here on the formulation of the VJP. The proof relies on the existence of partial derivatives of s(t,x,w)\s(t, \x, \w), which we do not cover here and refer to, e.g., Pontryagin (1985) for a complete proof of such facts given the assumptions.

We use the ODE constraint to introduce adjoint variables, this time in the form of a continuously differentiable function r\r. For any such function r\r, we have ⟨f(x,w),u⟩=⟨s(T,x,w),u⟩+∫0T⟨r(t),h(t,s(t,x,w),w)−∂ts(t,x,w)⟩dt,\begin{align*} \langle f(\x, \w), \u \rangle & = \langle \s(T, \x, \w), \u \rangle \\ & \quad + \int_0^T \langle \r(t), h(t, \s(t, \x, \w), \w) - \partial_t \s(t, \x, \w) \rangle dt, \end{align*} using Leibniz notations such as ∂ts(t,x,w)=∂1s(t,x,w)\partial_t \s(t, \x, \w) = \partial_1 \s(t, \x, \w). The VJPs then decompose as ∂wf(x,w)∗[u]=∂ws(T,x,w)∗u+∫0T(∂ws(t,x,w)∗∂sh(t,s(t,x,w),w)∗−∂wt2s(t,x,w)∗)r(t)dt+∫0T∂wh(t,s(t,x,w),w)∗r(t)dt,∂xf(x,w)∗[u]=∂xs(T,x,w)∗u+∫0T(∂xs(t,x,w)∗∂sh(t,s(t,x,w),w)∗−∂xt2s(t,x,w)∗)r(t)dt\begin{align*} & \partial_\w f(\x, \w)^*[\u] \\ & = \partial_\w \s(T, \x, \w)^* \u \\ & \quad + \int_0^T (\partial_\w \s(t, \x, \w)^* \partial_\s h(t, \s(t, \x, \w), \w)^* - \partial_{\w t}^2 \s(t, \x, \w)^* )\r(t) dt \\ & \quad + \int_0^T \partial_\w h(t, \s(t, \x, \w), \w)^* \r(t) dt, \\ & \partial_\x f(\x, \w)^*[\u] \\ & = \partial_\x \s(T, \x, \w)^* \u \\ & \quad + \int_0^T (\partial_\x \s(t, \x, \w)^* \partial_\s h(t, \s(t, \x, \w), \w)^* - \partial_{\x t}^2 \s(t, \x, \w)^* )\r(t) dt \end{align*} Here the second derivative terms ∂wt2s(t,x,w)∗r,∂xt2s(t,x,w)∗r\partial_{\w t}^2 \s(t, \x, \w)^*\r, \partial_{\x t}^2 \s(t, \x, \w)^*\r correspond to second derivatives of ⟨s(t,x,w),r⟩\langle \s(t, \x, \w), \r \rangle. Since the Hessian is symmetric (Schwarz’s theorem presented in Proposition 2.10), we can swap the derivatives in tt and w\w or x\x. Then, to express the gradient uniquely in terms of first derivatives of s\s, we use an integration by parts to have for example ∫0T∂wt2s(t,x,w)∗r(t)dt=∫0T∂tw2s(t,x,w)∗r(t)dt=(∂ws(T,x,w)∗r(T)−∂ws(0,x,w)∗r(0))−∫0T∂ws(t,x,w)∗∂tr(t)dt.\begin{align*} \int_0^T \partial_{\w t}^2 \s(t, \x, \w)^* \r(t)dt & = \int_0^T \partial_{t \w}^2 \s(t, \x, \w)^* \r(t)dt \\ & = ( \partial_{\w} \s(T, \x, \w)^* \r(T) - \partial_{\w} \s(0, \x, \w)^* \r(0) ) \\ & \quad - \int_0^T \partial_{\w} \s(t, \x, \w)^* \partial_t \r(t)dt. \end{align*} Since s(0)=x\s(0) = \x, we have ∂ws(0,x,w)∗r(0)=0\partial_{\w} \s(0, \x, \w)^* \r(0) = 0. The VJP w.r.t. w\w can then be written as ∂wf(x,w)∗[u]=∂ws(T,x,w)∗[u−r(T)]+∫0T∂ws(t,x,w)∗[∂sh(t,s(t,x,w),w)∗r(t)+∂tr(t)]dt+∫0T∂wh(t,s(t,x,w),w)∗r(t)dt.\begin{align*} & \partial_\w f(\x, \w)^*[\u] \\ & = \partial_\w \s(T, \x, \w)^* [\u- \r(T)] \\ & \quad + \int_0^T \partial_\w \s(t, \x, \w)^*[ \partial_\s h(t, \s(t, \x, \w), \w)^* \r(t) + \partial_t \r(t) ]dt \\ & \quad + \int_0^T \partial_\w h(t, \s(t, \x, \w), \w)^* \r(t) dt. \end{align*} By choosing r(t)\r(t) to satisfy the adjoint ODE ∂tr(t)=−∂sh(t,s(t,x,w),w)∗r(t),r(T)=u, \partial_t \r(t) = -\partial_\s h(t, \s(t, \x, \w), \w)^* \r(t), \quad \r(T) = \u, the expression of the VJP simplifies as ∂wf(x,w)∗[u]=∫0T∂wh(t,s(t,x,w),w)∗r(t)dt. \partial_\w f(\x, \w)^*[\u] = \int_0^T \partial_\w h(t, \s(t, \x, \w), \w)^* \r(t) dt. For the VJP w.r.t. x\x, we can proceed similarly. Using an integration by parts, we have, this time, ∂xs(0,x,w)∗r(0)=r(0)\partial_{\x} \s(0, \x, \w)^* \r(0) = \r(0) since s(0)=x\s(0) = \x. Choosing the same curve r(t)\r(t) satisfying the adjoint ODE we get ∂xf(x,w)∗[u]=r(0). \partial_\x f(\x, \w)^*[\u] = \r(0). The existence of a curve r\r solution of the backward ODE can easily be shown from Picard Lindelöf’s theorem and the assumptions.

12.7 Summary