Skip to content

Gradient rules, AD backends, executors and GPU arrays ​

Every call of an operator is differentiable by automatic differentiation (AD). This page states how the gradient of a call is computed, which AD backends are supported, and how the executors run a call on CPU threads and on GPU arrays. The API overview defines the terms used, and Performance gives the timings.

Rules and plain AD ​

Each operator call is differentiated in one of two ways.

  • The rule is a reverse pass written for the operator, which the Mooncake and Enzyme extensions register.

  • Under plain AD the backend differentiates the operator's forward loop.

A call takes the rule when each of its components takes it, as in the table below, and every float it holds is a Float16, Float32 or Float64. These floats may sit in an Array, a view or reshape of one, a sparse matrix or a Diagonal. Dual numbers, tracked values, BigFloat, abstractly typed fields and other array types take plain AD. The choice depends only on these types.

The rule of a Recurrence runs the step backwards in time, with the symbols defined there. With the cotangent of , each step from stop down to start computes

where is the modifiers' state and their pullback! methods in reverse tuple order. holds the cotangent of the output plus what later steps added to it. The coupling's pullback! for Pressure() gives and . The last line is for a kernel shared by every stratum.

A user-written coupling, modifier or depletion form takes the rule in one of two ways.

ComponentTakes the rule
modifier or depletion form written as a pure stepalways, by its local derivative or its step_pullback
coupling or modifier written with forward!with a pullback!, or declared islinear; otherwise plain AD

The package finds a component's pullback! from its methods, so writing the method is enough. gradient_routes gives the routes a recurrence can take, with the gradient time of each. A component declared linear runs as the matrix its forward! gives, built once per call outside the rule. A modifier that sets its starting state with forward! for Init() needs a pullback! for it too. A Derived parameter or kernel whose map holds floats sends the operator to plain AD, as no pullback reaches those floats.

The Recurrence constructor logs an @info when a component sends the operator to plain AD, naming the component and the reason. It logs each message once per session.

The rule also needs the call's numbers and arrays to be ones it can read and write. It takes IEEE floats and integers, held in an Array, a sparse matrix, a Diagonal, or a view, reshape, transpose or adjoint of an Array. A range, and a PermutedDimsArray, Symmetric or Hermitian of an Array, is copied to an Array on the way into the rule. The backend differentiates that copy, so a range built from parameters keeps their gradients. This holds for the kernel, the coupling, a modifier's parameters, the input and the history. A call with any other array type, such as a static array or a symmetric wrapper of a sparse matrix, takes plain AD. So does a call with a field of abstract type. A reverse-mode backend that would have run the rule then logs the same @info once, naming the field or argument and its type. A call on dual numbers or another number type that no rule runs takes plain AD by design and logs nothing.

The local derivative of a pure step ​

A pure step maps one stratum's value , state and parameters to a new value and state. The rule's reverse pass needs the product of its Jacobian's transpose with the output cotangents,

where a bar marks a cotangent and a prime the step's output. It takes that product from one evaluation of step on dual numbers, each float of seeded with a partial of its own. A group step seeds its group's values and state in the same pass, and more than 24 floats take further passes.

The local derivative reaches every field that is a parameter, or a tuple or named tuple of parameters. Integer fields, index ranges, integer arrays and functions without fields are structure, and reach the step unchanged. A float array that is not a parameter, or a closure that captures a float, is out of its reach, so such a modifier sends the operator to plain AD. Wrap an array in PerStratum or TimeVarying to make it a parameter.

The dual numbers compare by value only, as plain floats do. So at a tie, such as x > 0 ? y / x : zero(x) at x = 0, the derivative is that of the branch the step takes. A backend's own rule for a function with a kink can pick the other side, as for abs at zero and, on Mooncake, clamp at a bound. The same holds for a Transform whose map has no closed-form derivative.

Backends ​

BackendRulePlain AD
ForwardDiffneveralways, on dual numbers
ReverseDiffneveralways, on tracked values
Mooncake forwardneveralways
Enzyme forwardneveralways
Mooncake reversewhen the call takes the ruleotherwise
Enzyme reversewhen the call takes the ruleotherwise
Reactantneveralways, on the traced program

The supported backends are ForwardDiff, ReverseDiff, Mooncake and Enzyme, and the AD tests run each of them. ReverseDiff differentiates the plain code on tracked values, as a tape or a compiled tape. Forward-mode backends run the same forward code with or without the rule, so a rule only changes the cost of reverse mode. Forward mode costs one pass per parameter and reverse mode one pass per output, so forward mode is the cheaper for a model with few parameters. The AD comparison times every backend on the same scenarios.

Reactant traces a call into one compiled program and Enzyme differentiates that program, so the package's rules never run under it. Its support matrix gives the result of every scenario of the AD tests, forward and reverse. Most scenarios that do not run build components from traced values, such as sparse couplings and delay distributions, or branch with if on traced values in a modifier. A model that does not run under Reactant runs unchanged on the other backends.

Which rules are kept ​

A rule is kept only where it beats plain AD by about 10% in reverse mode on Mooncake or Enzyme. NoAdjoint wraps an operator so that its rules are turned off, which gives the plain AD time to compare with. The rule timings give each rule's time over that of plain AD.

Two rules stay on inside a NoAdjoint call.

  • Under Mooncake, a convolution adds each lag with axpy!, which Mooncake differentiates with its own rule.

  • Under Enzyme, a sparse route coupling's pressure is differentiated by the coupling's own pullback!.

Rules for building components before the call also stay: the masses of a chain of delays and the movement matrix of Redistribute(K, ε).

A recurrence of one stratum with one fixed lag, an I or λ * I coupling and no modifiers runs as a scan that keeps its running value in a register. Random walks, cumulative sums from a seed and AR(1) series take it. Mooncake takes the operator's rule for the scan, and Enzyme a rule on the scan alone.

Checking a rule ​

A rule is checked against plain AD through NoAdjoint. ComposableRecurrences.test_adjoint runs a backend's own rule tester on an operator's rule. The Mooncake and EnzymeTestUtils extensions add it.

Executors ​

An executor sets how an operator's loops over strata or output times run. EXECUTOR holds the one in use.

  • Serial runs each loop in order, and is the default.

  • Threaded splits a loop across CPU threads.

  • Parallel runs a loop as a kernel on a KernelAbstractions backend, such as a GPU.

On arrays that live on a GPU, Serial and Threaded both run as Parallel on the arrays' own backend.

Starting and joining tasks has a fixed cost, so Threaded runs a loop in order when its work is below min_work, 500 000 multiply-adds by default. The Threaded docstring states how the work of each loop is counted. The threshold is set per call:

julia
using Base.ScopedValues: with
using ComposableRecurrences: EXECUTOR, Threaded
with(EXECUTOR => Threaded(; min_work = 1_000_000)) do
    r(R; history = seed)
end

The executors support the backends as follows.

ExecutorForward runForwardDiffReverseDiffMooncake and Enzyme forwardMooncake and Enzyme reverse
Serial()yesyesyesyesyes
Threaded()yesyes, threadednot testedyes, serialthe rule's passes threaded, plain AD serial
Parallel(backend)yesdual-number inputsnot testednot testednot tested on a GPU

Mooncake and Enzyme do not differentiate tasks, so code they trace runs serially whatever executor is set. A rule's forward pass is not traced, so it uses the set executor, and its reverse pass splits the strata the same way. A coupling that mixes strata, a pairwise kernel, routes and modifiers that read across strata run their reverse steps on the calling task. Cotangents of parameters shared between threads are summed after the loop, so they agree with Serial() up to rounding. Cotangents of the inputs, the history and an S × T gain or add match exactly.

GPU arrays ​

A call on arrays that live on a GPU runs each loop over strata or output times as one kernel. The GPUArrays page has a runnable example.

  • Independent strata are one kernel per call, with each thread stepping its stratum through time.

  • The groups of a modifier that steps a group of strata, such as a Depletion with several pools, are one kernel per call, unless the call records a trace.

  • Strata that mix are one kernel per step, with the time loop on the host, so such a recurrence launches a kernel at every step.

Every array the call reads must live on the same device: the inputs, gain, add, history, a resumed state, the kernel, the coupling and the modifiers' parameters. A call that mixes device inputs with a host float array is an error. Adapt.adapt(CuArray, r) moves every parameter of an operator r to the device, and buffers, states and outputs are allocated from the inputs.

An output takes its float type from every array and number a call holds, so one Float64 scalar parameter, such as a population, promotes the run to Float64. convert_floats(Float32, r) converts every float of r, so Adapt.adapt(CuArray, convert_floats(Float32, r)) runs on the device in Float32.

Every operator, coupling and built-in modifier runs on a device, as do pressure, window_sums, kernel_weights and a convolution's transpose. Three restrictions apply.

  • A sparse coupling is a device sparse matrix in CSR form. Another device sparse form is converted to CSR when the recurrence is built, where the array package can convert it.

  • A user-written modifier type that holds arrays needs an Adapt.adapt_structure method. Arrays captured by the function of a Transform or Derived are not moved.

  • A user-written coupling, a modifier whose step runs on the whole vectors and an Init get the device vectors on the host. Their forward! must use array operations, such as broadcasts and mul!, as a loop over entries stops with a scalar-indexing error. A pointwise or blockwise modifier's step runs inside a kernel, so it may loop over its entries.

The package's rules run on device arrays for these calls.

  • A convolution whose kernel is fixed, time-varying or computed from coefficients (a Survival or Derived kernel).

  • A recurrence with such a kernel or a Pairwise one, with an identity, scalar, Diagonal, dense or CSR coupling, fixed or over time, and with the built-in modifiers.

  • A recurrence over routes whose couplings are matrices on the device and whose kernels are fixed.

  • A user-written modifier that is a pure step, or that runs per stratum or on fixed groups of strata with scalar parameters.

  • pressure, window_sums, kernel_weights, a convolution's transpose and a run that returns its modifiers' traces.

These calls take plain AD on device arrays.

  • A kernel given by change points.

  • Routes with a coupling that is not a matrix, or with a time-varying kernel.

  • A Redistribute whose moves are a time-varying array.

  • A user-written modifier that works on the whole step, holds an array or has a pullback! for the whole step.

The forward run and the rules' passes are tested on JLArrays, which run kernels on the CPU. The reverse-mode backends are not tested on device arrays, and forward-mode derivatives there take dual-number inputs.