From first principles
Differentiate a scalar objective through a linear state equation
Suppose the state \(u\) solves \(K(p)u=f(p)\) for a given parameter vector, with nonsingular \(K\), and a scalar objective \(J(u,p)\) measures mismatch. A small parameter perturbation changes the state through both the load and the operator. Differentiating the balance gives
To obtain a scalar derivative without computing every state sensitivity, solve the transpose system \(K^T\lambda=J_u\) once. Substitution eliminates \(du\),
Each parameter then contributes through its derivatives of \(f,K,J\). The transpose is required even if the forward solver is more familiar; it moves the scalar objective’s weights backward through the linear response. A directional finite difference of the complete objective is an independent check on a computed adjoint gradient.
Background · Adjoint sensitivity
This operation maps a data-space vector back to parameter space. For a discretised physical model the chosen inner products determine the correct adjoint.
Derivation and applications
Propagate a terminal measurement backward through continuous time
Consider a scalar state satisfying \(\dot u=a(t)u+p\,b(t)\) over \(0\le t\le T\), with known initial state independent of \(p\). A sensor observes \(u(T)\), giving loss \(J=\tfrac12[u(T)-y]^2\). Assume continuous coefficients and exact evolution for this calculation. The forward derivative \(w=\partial u/\partial p\) satisfies an inhomogeneous initial-value problem, and the objective derivative depends on its endpoint,
Instead of solving for every possible forcing sensitivity separately, introduce a terminal weight \(\lambda(T)=u(T)-y\). Choose its evolution to cancel the term proportional to \(w\) in the derivative of \(\lambda w\). The product rule gives
Integrate over the interval. The initial product vanishes because \(w(0)=0\), and the terminal product equals the desired gradient. Thus
One backward weight suffices for many scalar parameters entering through different forcing shapes. A parameter-dependent initial condition would add \(\lambda(0)\partial_pu(0)\). A discrete time integrator approximating the continuous equations also introduces integration error; differentiating the actual discrete steps gives the derivative of the computed loss at that finite step size.
Worked example
Reconstruct a sensitivity in a decaying reservoir
For \(a=-1,\ b=1,\ T=\ln 2,\ u(0)=0,\ p=4\), the terminal state is
With observation \(y=1.5\), the terminal adjoint is \(0.5\). Earlier weights are \(\lambda(t)=0.5e^{-(T-t)}\), so
Direct differentiation of \(\tfrac12(p/2-1.5)^2\) at four confirms the result.
Second application
Compare two controls observed only at the endpoint
For \(\dot u=-u\) between two instantaneous unit-gain input pulses, consider their amplitudes as independent parameters. A pulse at time \(t_i\) contributes \(e^{-(T-t_i)}\) to terminal-state sensitivity. At \(T=3\) with terminal residual 2, the gradient for a pulse at \(t=1\) is \(2e^{-2}=0.271\); for a pulse at \(t=2\) it is
Later forcing has greater leverage because it has less time to decay.
Does the gradient see where the instruments were actually placed?
A periodic ring of parameter nodes is mapped to fewer instrument readings in two operations. First a narrow, slightly asymmetric sensor spreads each nodal signal to its neighbours. Write this as a matrix \(S\). Next the instruments sample between nodes. For an instrument a fraction \(f\) of the way from node \(j\) to \(j+1\), the corresponding row of \(B\) has entries \(1-f\) and \(f\) at those nodes. The complete forward model is \(A=BS\). It is rarely necessary to assemble this product on a large mesh, but a small explicit example makes it possible to audit every entry.
Take Euclidean inner products so the conventions are clear. An adjoint must satisfy \((Av)^Tw=v^TA^Tw\) for every parameter direction \(v\) and sensor residual \(w\). Moving each matrix across the scalar product yields
The interpolation transpose scatters a sensor residual back to both neighbouring nodes with exactly the original weights. The smoothing transpose then exchanges the left and right coefficients of the stencil. Applying the forward smoothing again can look plausible and still shift the inferred sensitivity footprint.
Open full-size diagramTo test the gradient choose the merit function \(J(m)=\tfrac12\|Am-y\|^2\). Its directional derivative is \(v^TA^T(Am-y)\). Expand the quadratic objective exactly to find
Halving \(h\) divides the remainder by four until rounding intervenes. Substituting a wrong derivative leaves an extra term linear in \(h\). The notebook checks both the observed scaling and the coefficient of the quadratic term at one finite step. Several independent directions help avoid a chance cancellation in a single test.
With a fraction \(f=0.35\), one unit of observation residual is split into 0.65 and 0.35 before reverse smoothing. Its total remains one because the row weights sum to one, but conservation of that sum is a weak test: using the wrong asymmetric stencil also preserves it. If the underlying inversion uses volume-weighted mesh or measurement inner products, those weights must be included consistently; the plain transpose in this experiment applies to its explicitly chosen Euclidean metric.
The pictured footprint is obtained by sending a single residual backwards. It can also be reconstructed element by element by perturbing one parameter node forwards and recording just that sensor. The two pictures should agree for every node. This costs more forward evaluations, but on a small test ring it checks the location of a discrepancy directly.
Suppose the continuous forward code records a sensor at fraction 0.35 while its adjoint implementation rounds that sensor to the nearest node. Can an exact solution of the adjoint linear system repair the discrepancy?
Work through the solution
The error occurs in the observation operator itself. For a unit residual the true transpose must assign 0.65 and 0.35, whereas the rounded version assigns one and zero. Accurate solves propagate these different inputs accurately. An isolated dot-product test of the observation operator followed by a test of the full composition locates the discrepancy.
Change parameters · Explore this notebook example
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
The state is also a function of the parameters
Suppose a discretised forward model solves \(K(p)u=f(p)\). Data enter through \(Hu\), and observations have been whitened. The objective is \(J=\tfrac12\|Hu-y\|^2+R(p)\). A direct perturbation of a material parameter changes the predicted state even when that parameter never appears in the observation operator. For fixed \(H\), the state derivative contribution is \(g_u^\mathsf{T}du\), with \(g_u=H^\mathsf{T}(Hu-y)\). Differentiating the state equation gives
Solving this equation once per parameter would be prohibitively expensive for a fine material field.
Transpose the solve
Define an adjoint state by \(K^\mathsf{T}\lambda=g_u\). Then
For each parameter component the gradient is
This uses one forward and one transposed solve for one scalar objective, independent of the number of gradient components. Forming the contractions for all components still costs work, often local to mesh elements. If sensors or boundary conditions also depend explicitly on parameters, their derivative terms must be included. A symmetric diffusion operator may reuse a factorisation; an advection operator need not equal its transpose.
Work a two-cell example
Consider \(K=\left(\begin{smallmatrix}p+1&-1\\-1&2\end{smallmatrix}\right)\), \(f=(1,0)\), and observe the second component with value \(y=0.4\). At \(p=1\), \(u=(2/3,1/3)\), so the residual is \(-1/15\). The adjoint load is \((0,-1/15)\); solving gives \(\lambda=(-1/45,-2/45)\). Only the first diagonal entry of \(K\) depends on \(p\). With no regulariser the derivative is \(-\lambda_1u_1=2/135\). Check independently: \(u_2=1/(2p+1)\), whose derivative at one is \(-2/9\). Multiplying by the residual gives the same positive gradient. Increasing \(p\) lowers an already underpredicted second reading.
Test the computed gradient in a direction
Pick a physically scaled perturbation \(v\). A correct gradient gives a linear residual \(J(p+hv)-J(p)-h\,g^\mathsf{T}v\) of order \(h^2\) for a smooth problem. Halving \(h\) should roughly quarter this remainder across a useful range. At very small \(h\), forward-solver tolerances and floating-point cancellation can dominate. Repeat with directions touching different components and with the same boundary-condition handling used in production. A close fit to the observed data is a poor gradient test when residuals nearly vanish: a wrong data gradient can then look small by accident. Evaluate at a parameter away from the best fit, solve the state again for each perturbation and compare the resulting objective values. To detect a missing transpose, include a nonsymmetric forward operator in the test. The symmetric two-cell example above can expose a sign error but cannot distinguish the forward matrix from its transpose.
Reverse a sequence of state updates
Suppose the forward solver evolves \(u_{n+1}=G_n(u_n,p)\) for a fixed number of steps, and an objective sums observation losses \(\ell_n(u_n,p)\) from time zero to the final time. The direct chain rule carries a state derivative with respect to every parameter through the entire trajectory. To reverse the calculation, start with \(\lambda_N=\partial_{u_N}\ell_N\) as a column vector. A perturbation \(du_n\) affects both the loss at time \(n\) and the following state by \(G_{n,u}du_n\). Moving the latter action across a dot product gives the recursion \(\lambda_n=\partial_{u_n}\ell_n+G_{n,u}^T\lambda_{n+1}\).
The parameter gradient is the sum of explicit derivatives of all losses, the initial term \((\partial_p u_0)^T\lambda_0\), and the contributions \(G_{n,p}^T\lambda_{n+1}\) from every step. Each reversed step needs the state information used by its forward counterpart. Storing the whole trajectory makes that information available immediately. Recomputing segments between stored checkpoints trades extra forward evaluations for memory. These formulas differentiate the actual discrete transitions, so an adaptive solver with parameter-dependent step rejection or event switches needs a careful interpretation of the differentiated computation.
Make the transpose observable in a two-step calculation
Take a two-coordinate forward transition \(G(u,p)=Mu+pe_2\), with \(M=\left(\begin{smallmatrix}1&2\\0&1\end{smallmatrix}\right)\), \(u_0=0\), and \(p=1\). Two steps give
Observe the first coordinate only at the end, with target value one. The quadratic loss is one half and its final state derivative is
One reverse step gives
The two parameter contributions are \(e_2^T\lambda_2=0\) and \(e_2^T\lambda_1=2\), so the gradient is two.
The zero contribution from the last injection has a physical meaning: the injected second coordinate can influence the first only during a subsequent transition. The first injection has time to do that through the off-diagonal element two. Using \(M\) in place of \(M^T\) in the backwards calculation would instead keep \(\lambda_1=(1,0)^T\), predicting zero total sensitivity. This example exercises a distinction that disappears when every state matrix is symmetric.
For a scalar parameter perturbation \(h\), solving both steps again gives terminal first coordinate \(2(1+h)\) and loss \(J(1+h)=(1+2h)^2/2\). The remainder after subtracting the base loss and the predicted linear term is exactly \(2h^2\). For \(h=0.1\) and 0.05 the remainders are 0.02 and 0.005. The erroneous zero gradient instead gives 0.22 and 0.105. The two sequences have very different observed convergence factors even though they use identical forward trajectories and observation data.
More generally an individual parameter may enter the map at several times with different signs. The corresponding gradient terms must be accumulated rather than overwritten during the backward pass. In this example overwriting after the earliest step happens to return the correct value because the last contribution is zero. Adding a simultaneous observation of the final second coordinate makes both contributions nonzero and provides a complementary regression case for the time-index accumulation.
For a terminal loss summing both coordinate discrepancies, the adjoint load contains both sensor contributions before the first reverse transition.
Change parameters · Adjoint gradients through a forward solver
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Recognise an incorrect gradient by the rate of its remainder
Verify the reduced gradient for \(J(p)=(1/(p+2)-0.6)^2/2\) at \(p=1\). For each perturbation solve the scalar equilibrium again and subtract the original objective and the candidate linear term. The sign of the state sensitivity is essential.

Read values from the plot
| Parameter perturbation h | Correct gradient | Gradient with sign reversed |
|---|---|---|
| 3e−5 | 3.3334e−12 | 1.7778e−6 |
| 0.00028663 | 3.0431e−10 | 1.6985e−5 |
| 0.0027386 | 2.7795e−8 | 0.00016226 |
| 0.026166 | 2.5501e−6 | 0.001548 |
| 0.25 | 0.00024107 | 0.014574 |