Skip to content
QFT.org

Search QFT.org

Enter a word or phrase.

    You can also browse the main navigation and chapter contents.

    Forward and Reverse Automatic Differentiation

    A lattice action is a short program, but its derivative receives contributions from every link meeting a site. Automatic differentiation (AD) propagates the chain rule through that program. It can compute the force needed by an optimizer without choosing a finite-difference step, and it can differentiate an observable with respect to fields, couplings and sources in the same calculation.

    We develop both forward and reverse propagation, implement them on a periodic scalar action, and compare their derivatives with an independent calculation. The comparison also shows what AD does not establish: the derivative of a finite lattice program is not automatically the derivative of a continuum observable.

    Preparation: Multivariable differentiation and the scalar action in the conventions. The calculation uses real variables and a fixed lattice.

    A scalar action as a differentiable program

    Let qjq_j be a real field on NN periodic sites, with spacing aa, circumference L=NaL=Na and qN=q0q_N=q_0. Define the action including its source term by

    Sa(q,m2,λ,J)=a∑j=0N−1[(qj+1−qj)22a2+m2qj22+λqj424−Jjqj].(1)S_a(q,m^2,\lambda,J) =a\sum_{j=0}^{N-1}\left[ \frac{(q_{j+1}-q_j)^2}{2a^2} +\frac{m^2q_j^2}{2}+\frac{\lambda q_j^4}{24}-J_jq_j \right]. \tag{1}

    The minus sign on JqJq means that e−Sae^{-S_a} has the site's Euclidean source factor e+a∑Jqe^{+a\sum Jq}. The quartic normalization is λ/4!\lambda/4!. We also evaluate the neighboring-field quantity

    O(q)=1N∑jqjqj+1,F(x)=(Sa,O),x=(q0,…,qN−1,m2,λ,J0,…,JN−1).(2)O(q)=\frac1N\sum_jq_jq_{j+1},\qquad \mathcal F(x)=(S_a,O),\qquad x=(q_0,\ldots,q_{N-1},m^2,\lambda,J_0,\ldots,J_{N-1}). \tag{2}

    Here OO is a function of one supplied field configuration. It is not an ensemble-averaged correlation function. Both outputs are built from additions, multiplications and constant powers. This makes them a useful first example of a program whose derivatives can be checked completely.

    An independent differentiation gives

    ∂Sa∂qj=a[2qj−qj−1−qj+1a2+m2qj+λqj36−Jj],(3)\frac{\partial S_a}{\partial q_j} =a\left[\frac{2q_j-q_{j-1}-q_{j+1}}{a^2} +m^2q_j+\frac{\lambda q_j^3}{6}-J_j\right], \tag{3}

    and

    ∂Sa∂m2=a2∑jqj2,∂Sa∂λ=a24∑jqj4,∂Sa∂Jj=−aqj.(4)\frac{\partial S_a}{\partial m^2}=\frac a2\sum_jq_j^2, \qquad \frac{\partial S_a}{\partial\lambda}=\frac a{24}\sum_jq_j^4, \qquad \frac{\partial S_a}{\partial J_j}=-aq_j. \tag{4}

    The derivative of OO is (qj−1+qj+1)/N(q_{j-1}+q_{j+1})/N with respect to qjq_j, and zero with respect to all the coupling and source coordinates. These formulas will test the AD implementation; they are not substituted for its output.

    Forward propagation carries a direction

    Suppose a program evaluates intermediate values viv_i from earlier values. Attach a tangent v˙i\dot v_i, representing the response to one chosen change of the input. For an elementary operation,

    vi=φi(vj1,…,vjr)⟹v˙i=∑k=1r∂φi∂vjkv˙jk.(5)v_i=\varphi_i(v_{j_1},\ldots,v_{j_r}) \quad\Longrightarrow\quad \dot v_i=\sum_{k=1}^r \frac{\partial\varphi_i}{\partial v_{j_k}}\dot v_{j_k}. \tag{5}

    For example, the product rule updates a value–tangent pair as

    (u,u˙)(v,v˙)=(uv,u˙ v+u v˙).(6)(u,\dot u)(v,\dot v) =(uv,\dot u\,v+u\,\dot v). \tag{6}

    This is ordinary arithmetic on dual numbers u+ϵu˙u+\epsilon\dot u with ϵ2=0\epsilon^2=0. The symbol ϵ\epsilon is algebraic; it is not a small floating-point perturbation. A smooth elementary function acts as f(u+ϵu˙)=f(u)+ϵf′(u)u˙f(u+\epsilon\dot u)=f(u)+\epsilon f'(u)\dot u. See Baydin et al., §3.1 and §3.1.1, Eqs.(4)–(5) (PDF).

    Writing the Jacobian as Jαi=∂Fα/∂xi\mathsf J_{\alpha i}=\partial\mathcal F_\alpha/\partial x_i, initialize the input tangents with a vector vv. One forward sweep returns

    F˙=Jv.(7)\dot{\mathcal F}=\mathsf Jv. \tag{7}

    This Jacobian–vector product, or JVP, requires no explicit Jacobian. Seeding each coordinate direction in turn constructs the full Jacobian, one column per sweep. When there are few input directions and many outputs, forward mode is a natural choice.

    Our companion's Dual type implements these rules for scalar arithmetic, constant powers, square root, logarithm and sine. Replacing the numerical inputs to the same action function by dual inputs executes the actual derivative calculation. An array of precomputed analytic gradients would not be this test.

    Reverse propagation carries an output covector

    For a scalar weighted output ℓ=wTF\ell=w^{\mathsf T}\mathcal F, associate an adjoint vˉi=∂ℓ/∂vi\bar v_i=\partial\ell/\partial v_i with each intermediate value. After evaluating and recording the forward operations, traverse them in reverse order:

    vˉjk+=vˉi∂φi∂vjk.(8)\bar v_{j_k}\mathrel{+}= \bar v_i\frac{\partial\varphi_i}{\partial v_{j_k}}. \tag{8}

    The accumulation sign matters. An intermediate value may feed several later operations, and every path contributes. For z=uvz=uv, for instance, the reverse updates are uˉ+=vzˉ\bar u\mathrel{+}=v\bar z and vˉ+=uzˉ\bar v\mathrel{+}=u\bar z.

    Initialize the output adjoints with ww and all other adjoints with zero. The result at the inputs is

    xˉ=JTw.(9)\bar x=\mathsf J^{\mathsf T}w. \tag{9}

    This is a vector–Jacobian product (VJP), conventionally written wTJw^{\mathsf T}\mathsf J when covectors are rows. We store it as a column. One reverse sweep gives all input sensitivities of one scalar objective. The price is access to the forward values needed by the local partial derivatives, through storage or recomputation. The tape construction and reverse accumulation are described in Baydin et al., §3.2 (PDF).

    The implementation stores each scalar value, its parent node indices and the corresponding local partials. It performs Eq.(8) literally. A small field program is a useful place to inspect this mechanism before relying on a large AD library.

    For nn inputs and mm outputs, a full Jacobian generally needs nn scalar-seeded forward sweeps or mm scalar-seeded reverse sweeps. A single JVP or VJP needs only its requested direction. Vectorization, storage, sparsity and recomputation affect the cost of each sweep.

    A checked lattice calculation

    Use N=8N=8, a=0.5a=0.5, m2=1m^2=1 and λ=4\lambda=4, in fixed numerical units. The supplied fields and sources are

    qj=0.2+0.3cos⁡2πjN−0.15sin⁡4πjN,Jj=0.1cos⁡2πjN.(10)q_j=0.2+0.3\cos\frac{2\pi j}{N}-0.15\sin\frac{4\pi j}{N}, \qquad J_j=0.1\cos\frac{2\pi j}{N}. \tag{10}

    There are 1818 input coordinates. In their stated Euclidean coordinate norm, choose the unit vector proportional to

    vi∝sin⁡(i+1)+0.3cos⁡(2i+1),i=0,…,17,w=(0.7,−1.2).(11)v_i\propto\sin(i+1)+0.3\cos(2i+1),\qquad i=0,\ldots,17, \qquad w=(0.7,-1.2). \tag{11}

    Changing the units or scaling of these mixed field and coupling coordinates would change the meaning of this direction; none is left implicit. The calculated values are

    F=(0.53766853421235,  0.07181980515339),Jv=(0.81026693525719,  0.08588547359869).(12)\mathcal F=(0.53766853421235,\;0.07181980515339), \qquad \mathsf Jv=(0.81026693525719,\;0.08588547359869). \tag{12}

    The maximum entrywise differences from the analytic Jacobian are 1.11×10−161.11\times10^{-16} for forward mode and 1.67×10−161.67\times10^{-16} for reverse mode in this binary64 run. The pairing check

    wT(Jv)=vT(JTw)(13)w^{\mathsf T}(\mathsf Jv)=v^{\mathsf T}(\mathsf J^{\mathsf T}w) \tag{13}

    has absolute discrepancy 1.11×10−161.11\times10^{-16}. The derivatives of OO with respect to all ten non-field inputs are exactly zero in the recorded output. This last check tests that the program has not introduced a spurious dependency.

    The recorded reverse tape has 217217 nodes, including input and constant nodes, with 171171 operation nodes and 277277 parent edges. Constructing the complete 2×182\times18 Jacobian takes 1818 forward sweeps or two reverse sweeps.

    Finite differences test a different source of error

    A centered directional difference estimates the same derivative by

    DhF(x;v)=F(x+hv)−F(x−hv)2h.(14)D_h\mathcal F(x;v)=\frac{\mathcal F(x+hv)-\mathcal F(x-hv)}{2h}. \tag{14}

    For sufficiently smooth functions in exact arithmetic, its error is O(h2)O(h^2). Floating-point subtraction introduces an error that typically grows as hh decreases. AD has no step-size truncation error, but its values and local derivatives still accumulate rounding error.

    hh∥DhF−Jv∥∞\lVert D_h\mathcal F-\mathsf Jv\rVert_\infty
    10−110^{-1}2.3082×10−42.3082\times10^{-4}
    10−310^{-3}2.3082×10−82.3082\times10^{-8}
    10−510^{-5}1.1319×10−121.1319\times10^{-12}
    10−710^{-7}5.9839×10−105.9839\times10^{-10}
    10−910^{-9}2.6134×10−82.6134\times10^{-8}
    Centered directional differences initially converge quadratically and then lose accuracy, while the AD analytic-Jacobian discrepancy is near machine roundoff.

    The fixed action of Eq.(1), with the inputs and direction of Eqs.(10)–(11). The solid curve compares the directional finite difference with the AD JVP. The dashed line is the separate maximum entrywise forward-AD versus analytic-Jacobian discrepancy; it is a roundoff diagnostic, not a bound on every derivative calculation.

    The reproducible autodiff.py, scalar_action.py, autodiff_checks.py and selected autodiff-results.json are in examples/computational-qft/optimization/. The primitive and shared-node tests supplement the field calculation. No sampling, minimization or continuum extrapolation is involved.

    Which mathematical function is differentiated?

    AD applies the chain rule to the smooth operations of the executed trace, evaluated with finite-precision numbers. It does not differentiate the discontinuous rounding map as a mathematical function. Nor does it establish that two programs which differ by clipping, a changed boundary condition or a stopped iterative solve represent the same target.

    If a branch is locally unchanged, differentiating its executed smooth formula can be appropriate. At a switching surface the requested derivative may be one-sided, undefined or different from the derivative of that branch. Likewise, AD through nn solver iterations differentiates those nn iterations. The derivative of their limiting root requires convergence and conditioning arguments, developed in implicit differentiation. Time evolution introduces the analogous choice between the finite time-step map and the differential equation; adjoint field methods makes that distinction explicit.

    Summary

    Forward AD propagates an input direction and returns Jv\mathsf Jv. Reverse AD accumulates an output covector and returns JTw\mathsf J^{\mathsf T}w. Both differentiate the same finite program without a finite-difference step. The scalar example checks link contributions, source signs, coupling factors, zero dependencies and directional pairing independently. Accuracy of that derivative remains distinct from accuracy of the physical discretization or model.

    Exercises

    1. Derive the force and its free Fourier spectrum

    Derive Eq.(3), including both adjacent links. Find the coordinate Hessian at q=0q=0 and its eigenvalues on periodic Fourier modes. Explain the difference between the coordinate gradient and the gradient in the inner product ⟨u,v⟩a=a∑jujvj\langle u,v\rangle_a=a\sum_ju_jv_j.

    Solution

    The two gradient terms containing qjq_j are (qj−qj−1)2/(2a)(q_j-q_{j-1})^2/(2a) and (qj+1−qj)2/(2a)(q_{j+1}-q_j)^2/(2a). Their derivatives add to (2qj−qj−1−qj+1)/a(2q_j-q_{j-1}-q_{j+1})/a. Adding the on-site derivatives gives Eq.(3); the quartic factor is 4/24=1/64/24=1/6 and the source derivative is −aJj-aJ_j.

    For arbitrary qq, the coordinate Hessian is

    ∂2Sa∂qj∂qk=a[2δjk−δj−1,k−δj+1,ka2+(m2+λ2qj2)δjk].\frac{\partial^2S_a}{\partial q_j\partial q_k} =a\left[\frac{2\delta_{jk}-\delta_{j-1,k}-\delta_{j+1,k}}{a^2} +\left(m^2+\frac\lambda2q_j^2\right)\delta_{jk}\right].

    At q=0q=0, substituting uj=e2πinj/Nu_j=e^{2\pi i n j/N} gives the coordinate eigenvalue

    a[m2+4a2sin⁡2πnN].a\left[m^2+\frac4{a^2}\sin^2\frac{\pi n}{N}\right].

    The aa-weighted gradient is defined by δSa=⟨∇aSa,δq⟩a\delta S_a=\langle\nabla_aS_a,\delta q\rangle_a, so it is a−1a^{-1} times the coordinate gradient. Its linearization has eigenvalues m2+4a−2sin⁡2(πn/N)m^2+4a^{-2}\sin^2(\pi n/N). Mixing these two gradients would change an optimization step or force by a spacing-dependent factor.

    2. Follow a shared intermediate in both directions

    For z=xyz=xy and f=z2+sin⁡zf=z^2+\sin z, compute the JVP along (x˙,y˙)=(vx,vy)(\dot x,\dot y)=(v_x,v_y) and the VJP with scalar output seed ww. Show why overwriting the reverse adjoint of zz gives a wrong answer, and verify the pairing identity.

    Solution

    Forward propagation gives

    z˙=yvx+xvy,f˙=(2z+cos⁡z)(yvx+xvy).\dot z=yv_x+xv_y, \qquad \dot f=(2z+\cos z)(yv_x+xv_y).

    There are two paths out of zz: one through the square and one through the sine. In reverse order their contributions must add:

    zˉ=2zw+wcos⁡z,xˉ=yw(2z+cos⁡z),yˉ=xw(2z+cos⁡z).\bar z=2zw+w\cos z, \qquad \bar x=yw(2z+\cos z), \qquad \bar y=xw(2z+\cos z).

    If the square is implemented as z⋅zz\cdot z, both parent edges also contribute separately, each by zwzw. An assignment in place of accumulation would lose at least one path. Finally,

    wf˙=vxxˉ+vyyˉ,w\dot f=v_x\bar x+v_y\bar y,

    which proves the JVP/VJP pairing for arbitrary seeds. The retained test uses x=0.7x=0.7, y=−0.4y=-0.4 and an actual sine primitive on the tape, rather than replacing this trace by its simplified derivative.

    References

    • Atılım Güneş Baydin, Barak A. Pearlmutter, Alexey Andreyevich Radul and Jeffrey Mark Siskind, Automatic Differentiation in Machine Learning: a Survey, JMLR 18(153), 1–43 (2018), §3.1, Eq.(4), §3.1.1, Eq.(5), and §3.2 (PDF). These sections explain forward dual propagation and reverse accumulation. The lattice program and its checks are derived here.

    Scrollable formula. Use Left and Right arrow keys to reveal hidden content.

    Scrollable table. Use Left and Right arrow keys to reveal hidden columns.

    Scrollable figure. Use Left and Right arrow keys to reveal hidden content.