Performance and trimming
The speed of a new type depends on its methods allocating nothing and on its field types being concrete. The sections below give those requirements, the measured cost of a modifier's gradient by route, the check for trimmed executables and the way to specialise a method for one type.
Fast methods
A
stepallocates nothing and writes nothing, so that it is a pure function of its arguments.A
forward!orpullback!of a coupling or whole-step modifier allocates nothing: it loops witheachindexover the arrays it indexes, writes in place, and uses@inboundsonly in such loops.Field types are concrete through type parameters, so that every call is type stable.
The cost of a gradient by route
A route is the way the gradient of an operator with a user's modifier is computed. There are three.
Plain AD: the backend differentiates the code of the whole operator, which
NoAdjointselects.steponly: the operator's rule runs, and differentiatesstepwith its local derivative, one forward-mode pass per stratum and time.step_pullback: the rule runs, and calls the modifier'sstep_pullbackin place of the local derivative.
The example is a user's copy of the built-in hazard depletion, a step with state that calls exp and expm1,
where Depletion(N) with its default Hazard form, which has a rule of its own in the package, so the user's routes are compared with it.
# A user copy of the built-in hazard depletion: the draw
# `y = s (1 - exp(-v / N))` from the pool `s`, which keeps `s exp(-v / N)`.
struct Draw{T, P}
N::T
pool::P
end
# The same step, with a hand-written `step_pullback`.
struct DrawPullback{T, P}
N::T
pool::P
end
const _Drawing = Union{Draw, DrawPullback}
CR.init(::_Drawing, θ, history) = θ.pool
# One call gives both `exp(-x) - 1` and `exp(-x)`.
function CR.step(::_Drawing, θ, v, s)
em = expm1(-v / θ.N)
return -s * em, s * (em + 1)
end
# With `x = v / N`: ∂y/∂x = -∂s′/∂x = s exp(-x), ∂y/∂s = 1 - exp(-x) and
# ∂s′/∂s = exp(-x).
function CR.step_pullback(::DrawPullback, θ, v, s, v̄′, s̄′)
x = v / θ.N
em = expm1(-x)
e = em + 1
x̄ = s * e * (v̄′ - s̄′)
return x̄ / θ.N, s̄′ * e - v̄′ * em, (; N = -x̄ * x / θ.N)
end
The model is a seeded renewal with this depletion, the case renewal_depletion of the benchmark matrix and its two copies user_depletion and user_depletion_pullback. The table gives the minimum time of one call in microseconds: the forward run, and the gradient with respect to the kernel, the seed and the gain on each backend. The hand loop is the same model written as one loop without the package, differentiated by plain AD, and the hand rule is a hand-written Mooncake rule for that loop.
| Route | forward run | ForwardDiff | Mooncake reverse | Enzyme reverse |
|---|---|---|---|---|
| built-in rule | 9.08 | 515.0 | 25.6 | 18.4 |
| user step_pullback | 10.7 | 535.0 | 24.9 | 18.1 |
| user step only | 8.79 | 518.0 | 25.5 | 19.2 |
| hand loop | 12.7 | 524.0 | 103.0 | 31.5 |
| plain AD | – | 527.0 | 81.3 | 23.4 |
| hand loop with hand rule | – | – | 31.6 | – |
The times are from one run of task -t benchmark/Taskfile.yml matrix-extension at T 200 and L 20, one stratum, revision 880c6024, Julia 1.13.4, on one core of this CPU: Intel(R) Xeon(R) Processor @ 2.10GHz.
Three ratios summarise the table. The time with step only over the time of plain AD is 0.31 on Mooncake and 0.82 on Enzyme. The time with the step_pullback over the time with step only is 0.97 on Mooncake and 0.94 on Enzyme. The time with the step_pullback over the time of the built-in rule is 0.97 on Mooncake and 0.98 on Enzyme.
A ratio between 0.9 and 1.1 is not distinguished from the variation between runs. Against plain AD, the time with step only is lower on Mooncake and lower on Enzyme. Against step only, the time with the step_pullback is the same on Mooncake and the same on Enzyme. Against the built-in rule, the time with the step_pullback is the same on Mooncake and the same on Enzyme.
The local derivative of a step costs one evaluation of the step on dual numbers, so a step_pullback saves time only where its closed form costs less than that evaluation. The ForwardDiff column has no rule: forward-mode differentiation runs the same code by every route.
The second example is a step of a few operations. The saturation benchmark/docs_modifier.jl keeps no state and calls no special function.
| Route | forward run | ForwardDiff | Mooncake reverse | Enzyme reverse |
|---|---|---|---|---|
| user step_pullback | 4.04 | 510.0 | 21.2 | 10.3 |
| user step only | 4.06 | 506.0 | 22.2 | 10.6 |
| plain AD | – | 512.0 | 83.4 | 18.2 |
For the saturation, the time with the step_pullback over the time with step only is 0.95 on Mooncake and 0.97 on Enzyme.
A step_pullback is therefore added only where a benchmark shows a gain, or where the local derivative fails (A form at an empty pool). gradient_routes times the routes of a user's own model in one call. The cases above are in the tier the benchmark workflow times on each change, so a change in the cost of any route is reported there.
Parity with a built-in
The user's copy of the hazard depletion, with its step_pullback, a trace and an Adapt.adapt_structure method, is run beside the built-in Depletion on each way a model is run. The model has per-stratum populations and starting pools, a kernel of 20 lags and 200 steps, on 5 strata where the row does not say. The column Agree says whether the two give the same output, trace or gradient to a relative 1e-8. The times are the fastest call in microseconds, the ratio is the user copy's time over the built-in's, and the band is the largest ratio between the built-in's own two times in a round. A ratio is told apart from one when it lies outside its band and outside 0.9 to 1.1.
| Run | Agree | Built-in | User copy | Ratio | Band |
|---|---|---|---|---|---|
| forward run, 1 strata | yes | 7.35 | 7.32 | 1.00 | 1.00 |
| forward run, 5 strata | yes | 18.9 | 19.4 | 1.03 | 1.02 |
| forward run, 50 strata | yes | 180.0 | 181.0 | 1.01 | 1.00 |
| forward run, Threaded, 50 strata | yes | 184.0 | 179.0 | 0.97 | 1.01 |
| forward run, record = Trace() | yes | 23.6 | 24.1 | 1.02 | 1.02 |
| forward run, resumed at half | yes | 20.4 | 20.6 | 1.01 | 1.03 |
| gradient, ForwardDiff | yes | 7100.0 | 6980.0 | 0.98 | 1.04 |
| gradient, Mooncake reverse | yes | 92.0 | 90.9 | 0.99 | 1.01 |
| gradient, Mooncake forward | yes | 71200.0 | 68800.0 | 0.97 | 1.17 |
| gradient, Enzyme reverse | yes | 77.4 | 75.2 | 0.97 | 1.02 |
| gradient, Enzyme forward | yes | 22300.0 | 21200.0 | 0.95 | 1.11 |
| gradient through Trace(), Mooncake reverse | yes | 108.0 | 115.0 | 1.06 | 1.01 |
| gradient in a history of 400, Mooncake reverse | yes | 94.6 | 94.8 | 1.00 | 1.01 |
| forward run, JLArray | yes | 1730.0 | 1800.0 | 1.04 | 1.09 |
| rule passes, JLArray | yes | 7350.0 | 7070.0 | 0.96 | 1.08 |
The times are from one run of benchmark/parity.jl at revision 7e6061dd, Julia 1.13.4, with 4 threads on this CPU: Intel(R) Xeon(R) Processor @ 2.10GHz. No ratio is told apart from one.
A gradient through the trace is the row where a user's step differs most from the built-in, by the ratio in the table. The reverse pass differentiates a user's trace by one pass of dual numbers, and adds the cotangent of each parameter whether or not the trace reads it. The built-in's trace has a closed-form derivative.
The tests in test/unit/parity.jl hold the agreement, and the cases renewal_depletion and user_depletion_pullback of the benchmark matrix hold the times. JLArrays runs each kernel on the CPU, so the two device rows compare the kernels' overhead and not times on a GPU.
Trimmed executables
juliac --trim=safe compiles an app into an executable that holds only the code the app can reach. The build fails on any call the compiler cannot resolve from the argument types. A build can pass and the executable still fail, for example on a call the runtime makes, so the check runs the app as well as building it.
The app in test/trim checks the forward path of each operator, a depletion with flows, a derived parameter and a Threaded loop. The Trim workflow builds and runs it when src or the app changes. Its operator calls run serially, as a trimmed app cannot set EXECUTOR with with on Julia 1.12, and gradients and the extensions are not trim-tested. A new type used in a trimmed app needs concrete field types, and methods whose calls resolve from the argument types.
To run the check locally, with JuliaC installed in a shared environment:
julia --project=@juliac -e 'using Pkg; Pkg.add("JuliaC")'
cd test/trim
julia --project=. -e 'using Pkg; Pkg.instantiate()'
julia --project=@juliac -e 'using JuliaC; JuliaC.main(ARGS)' -- \
--output-exe trimapp --bundle build --trim=safe --experimental .
build/bin/trimappSpecialising for speed
Every call of an operator has one form, and the work behind it is chosen by dispatch on the types of its kernel, coupling, modifiers and numbers. A method for a narrower type replaces the general one for that type alone, so a faster path for one combination needs no new interface and no change to any call.
| To speed up | Add a method |
|---|---|
| a coupling with structure, such as low rank or banded | forward!(C::MyCoupling, Pressure(), q, p, t), and its pullback! |
| a modifier or depletion form at one parameter form | step(m::MyModifier{<:PerStratum}, θ, v, s), typed in the modifier only |
| the derivative of a pure step | step_pullback(m::MyModifier, θ, v, s, v̄′, s̄′), where timing shows it is faster |
A rank-one coupling
where
struct RankOne{V}
u::V
w::V
end
function CR.forward!(C::RankOne, ::CR.Pressure, q, p, t)
c = zero(eltype(q))
for b in eachindex(p)
c += C.w[b] * p[b]
end
for a in eachindex(q)
q[a] = C.u[a] * c
end
return nothing
end
u, w = [0.9, 0.1, 0.4], [0.5, 0.3, 0.2]
R = fill(1.2, 3, 6)
h = ones(3, 2)
low = Recurrence([0.5, 0.5]; coupling = RankOne(u, w))(R; history = h)
dense = Recurrence([0.5, 0.5]; coupling = u * w')(R; history = h)
low ≈ densetrueThe package specialises its own internal code the same way, in _kdot, _independent, _series_body!, _convolve_series! and _public, which may change without notice.