Testing and benchmarking
A new modifier, coupling or depletion form is checked against PieceInterface, and its gradient against ForwardDiff and against plain automatic differentiation (AD) of the operator's code. The benchmark matrix times every operator on each backend, and benchmark/ab.jl compares two revisions.
Comparing with plain automatic differentiation
NoAdjoint wraps an operator so that a backend differentiates its code and does not take its rule.
using ComposableRecurrences
using ComposableRecurrences: NoAdjoint, Depletion
using ForwardDiff, Chairmarks
r = Recurrence([0.2, 0.5, 0.3]; modifiers = (Depletion(1000.0),))
loss(op) = R -> sum(op(R; history = fill(5.0, 3)))
R = fill(1.4, 60)
(
operator = @b(ForwardDiff.gradient($(loss(r)), $R), seconds = 0.2).time,
no_adjoint = @b(ForwardDiff.gradient($(loss(NoAdjoint(r))), $R), seconds = 0.2).time,
)(operator = 1.2639e-5, no_adjoint = 1.2519000000000002e-5)A rule is timed on a reverse-mode backend, as forward-mode backends do not take it.
Rule timings
A rule is kept only where it beats plain AD by about 10% in reverse mode on Mooncake or Enzyme. The table gives the rule time over the NoAdjoint time, from benchmark matrix cases at T 200 and L 20 where one covers it, else from the small CI scenarios (marked ¹).
| Rule switched on by | Mooncake reverse | Enzyme reverse | Decision |
|---|---|---|---|
core recurrence (kernel, I or dense coupling) | 0.44 | 0.84 | keep |
Depletion, hazard form | 0.16 | 0.31 | keep |
Depletion, Floor(), dense coupling | 0.32 | 0.39 | keep |
Depletion, Truncate(), dense coupling | 0.20³ | 0.24³ | keep |
Depletion, Truncate(κ), dense coupling | 0.20³ | 0.32³ | keep |
Depletion with two pools and a count flow | 0.28 | 0.40 | keep |
Redistribute | 0.07 | 0.35 | keep |
Depletion without a draw | 0.43 | 0.43 | keep |
Depletion with two pools and waning | 0.40 | 0.32 | keep |
Allocate | 0.32¹ | 0.23¹ | keep |
Allocate with imports and spill, 64 strata | 0.05 | 0.11 | keep |
Depletion filled up to a capacity, flows before the draw | 0.26 | 0.32 | keep |
Transform | 0.18 | 0.43 | keep |
Primary() kernel | 0.51 | 0.66 | keep |
Pairwise kernel | 0.20¹ | 0.18¹ | keep |
Pairwise routes, dense and sparse, 50 strata | 0.11 | 0.45 | keep |
Diagonal coupling | 0.34¹ | 0.48¹ | keep |
| sparse coupling | 0.29¹ | 0.12¹ | keep |
TimeVarying kernel and coupling | 0.29¹ | 0.44¹ | keep |
Convolution | 0.48 | 0.64 | keep |
| a sparse route coupling under plain AD | plain AD | 0.48 to 0.57⁶ | keep on Enzyme |
¹ The scenario's function and its NoAdjoint twin's, each called directly.
³ A local timing, not a matrix case: 5 strata, a dense coupling, T 200 and L 20.
⁶ A local timing, not a matrix case: a NoAdjoint call of the strata_routes routes without the depletion, at T 200 and L 20, timed with and without the rule. It was timed at 5 and 50 strata, with the sparse route coupling constant and as a parameter.
Every rule is faster than plain AD on each backend that takes it; where the decision names one backend, the other takes plain AD.
A step_pullback is held to the same policy against the local derivative of its step. The script benchmark/step_pullback_ab.jl times a matrix case with the step_pullback of named types hidden, one arm per process. The table gives the fastest of two or three alternating runs with the local derivative over the fastest with the step_pullback, at T 200 and L 20.
| Step | Case | Mooncake reverse | Enzyme reverse | Decision |
|---|---|---|---|---|
Hazard | renewal_depletion, 1 stratum | 0.97 | 1.00 | keep, for the empty pool |
Hazard | bvd_patch, 5 strata | 1.02 | 1.04 | keep, for the empty pool |
Floor | strata_mixing, 5 strata | 0.98 | 1.03 | local derivative |
Transform(clamp, lo, hi) | renewal_clamp, 5 strata | 1.04 | 1.09 | local derivative |
Truncate | capacity_beds, 20 strata | 1.17 | 1.22 | keep the step_pullback |
Two runs of the same arm differ by up to 1.27 on the machine that timed them, so only Truncate shows a gain. The form Hazard keeps its step_pullback for the empty pool. With an exponent above one, the dual numbers multiply the zero pool by an infinite slope there, and its product form stays finite.
Comparing two revisions
benchmark/ab.jl times a base revision and a candidate revision on one machine, each in a fresh process, one process at a time. A round runs the base, the candidate and the base again, in an order that rotates by round. The two base runs time the same code, so their ratio measures the noise of the run, and a benchmark is reported as faster or slower only outside it.
julia benchmark/ab.jl --base=origin/main --cand=HEAD --rounds=3 \
--targets=primal,ForwardDiffThe report is written to ab-results/REPORT.md. A change made for speed is kept only with such a comparison, and with a stated cause for the difference.
The benchmark matrix
benchmark/matrix.jl times every case in test/ADFixtures/src/matrix_cases.jl at every size of a tier, on the primal run and each gradient backend, with and without NoAdjoint. Each backend runs in its own Julia process.
task -t benchmark/Taskfile.yml matrix -- --tier=ci --targets=primal
task -t benchmark/Taskfile.yml matrix-rules
task -t benchmark/Taskfile.yml matrix-report -- matrix-resultsThe report lists the median time of every cell, and the gain of each hand-written gradient as the NoAdjoint median over the operator's median. A new case is a Case entry in matrix_cases.jl whose loss takes a wrap argument (identity or NoAdjoint), so the matrix times both arms.
Some cases add arms:
Cases in
LOCAL_CASESrun alocalarm, which hides thestep_pullbackof each modifier that has one, so the rule takes its local derivative.The
bvd_renewal,bvd_patchesandbvd_delaycases time the model of the patch model case study, in therealisticanddocstiers. They add alooparm, a hand loop in the style of the BVDOutbreakSize backend. They also add ahandrulearm, the same loop with the hand-written Mooncake rules inbenchmark/bvd_handrule.jl.The cases in
TUTORIAL_HANDRULE_CASESadd ahandrulearm beside theirlooparm, with the rules inbenchmark/tutorial_handrule.jl.
The handrule arm runs on Mooncake reverse only, since on any other target it is the loop arm. A test item in test/ad/handrules.jl checks that each of these rules is a Mooncake primitive and that its gradient matches ForwardDiff on the case's hand loop.
--executor and --threads time the operators under an executor. --threads=1,2,4 runs each target once per thread count, and --executor=threaded runs the rule arm under Threaded() (the default is serial). Each run writes <tier>-<run>.tsv and <tier>-<run>.log, where <run> is the target with the thread count and any executor other than serial appended, such as primal_t4 or primal_Threaded_t4.
task -t benchmark/Taskfile.yml matrix -- --tier=realistic --targets=primal
task -t benchmark/Taskfile.yml matrix -- --tier=realistic --targets=primal \
--executor=threaded --threads=2,4The report adds an executor table with each threaded run's speed-up over the serial one-thread run of the same target. Write the serial one-thread run to the same directory first, or the report leaves the table out and says why. Serial runs on more than one thread are labelled <target> @ t<n> and stay out of the executor table. Under the Threaded() executor, ForwardDiff gradients run threaded, and Mooncake and Enzyme thread only a rule's forward and reverse passes. Each row records the load average when its cell started, so a busy machine shows in the results.
Gradient tests and use-case tests
test/ADFixtures holds the scenarios the gradient tests run on every backend, each checked against a ForwardDiff reference. The tolerances are:
Each gradient entry matches its reference to a relative
1e-8, or1e-4for a scenario with single-precision parameters. Entries that are zero in exact arithmetic have an absolute floor of1e-12. The plain call and the prepared, value-and-gradient and in-place calls are all checked this way.The ForwardDiff job checks each reference against central differences to a relative
1e-5, so a wrong reference cannot pass every backend. Each entry may also differ by the rounding of its central difference,100 eps |f| / hfor a steph. Each entry is tried at a step relative to it and at a step of at leastcbrt(eps()); a wrong reference misses by far more.The rule testers that
test_adjointruns use a relative and absolute1e-8, or1e-3in single precision, where their finite differences lose more.
A scenario is a name, a scalar loss of a flat parameter vector and its starting value, added to _SCENARIOS.
("Recurrence renewal", _renewal, () -> _flat(G0, zeros(L), LOGR[1, :]))ADFixtures.scenarios() gives each scenario's function as written, which is what the benchmarks time. ADFixtures.scenarios(; dynamic = true) gives it behind one dynamic call, which the gradient tests use so that Enzyme compiles a scenario once for every call a test makes. A backend pays a run-time lookup at that call, of a microsecond or more, so no benchmark takes it: ADFixtures.direct_call stops a timing run that does.
Run one backend with TAG=mooncake_reverse task test-ad-backend.
Where a new gradient test goes
Each backend job compiles every scenario and test item it runs, so a check in the AD jobs costs minutes on each backend. Put each check at the cheapest level that runs its code path.
The maths of a
step_pullbackorpullback!goes intest/unit, against a ForwardDiff Jacobian on small inputs. For a pure step, declare thestepcomponent ofPieceInterface, which compares astep_pullbackwith the forward-mode pass. For a modifier step, depletion form or coupling, declare thepullbackcomponent ofPieceInterfaceand test it withInterfaces.test(PieceInterface{(:pullback,)}, T, objs). For a whole call, usepullback_matches(test/unit/adjoints.jl). These need no AD backend.A new rule path, such as a new operator, a new kind of field or a new wrapper of the call, gets one small scenario in
_SCENARIOS. Every backend job runs it through its rule against ForwardDiff.Every scenario has a
NoAdjointtwin, which Mooncake reverse and Enzyme reverse run: there the twin is the only check that the backend differentiates a built-in's own forward code. ForwardDiff and the forward modes take the same plain path for a scenario and its twin, so they run the scenarios alone (category = :rules). A new method of a call onNoAdjointitself needs a check on each of these backends, in the item "Without a rule: the NoAdjoint wrapper's own calls". The benchmarks time every twin.test_adjointchecks one registry operator of each kind of field and wrapper, listed inADJOINT_SCENARIOSintest/ad/adjoints.jl. Add a scenario there only when it brings a kind of field or wrapper the list lacks, or a branch for a constant part that Enzyme's pass with the operator constant reaches.A failure on one backend gets an item tagged for that backend only, at the smallest size that shows it. Name the failure in a comment, so the item stays while the failure can come back.
Do not add a scenario that repeats a covered path at a larger size or in another combination. The benchmark matrix times realistic sizes.
test/usecases rebuilds real models from modelling packages with the operators and compares values and gradients with reference code in test/usecases/references. Run them with julia --project=test test/runtests.jl usecase_only.
Threads, older Julia versions and Reactant in CI
The Threads workflow runs the tests with four threads, so Threaded loops run on separate threads. On Julia 1.11 it runs the whole unit suite; on the current release it runs only the items tagged :threads, as the Test workflow runs the rest there. Tag an item :threads when it uses Threaded, EXECUTOR or Threads, so it runs with four threads on the current release too. A quality check in test/package/test_tags.jl fails on an item that uses them without the tag. To do the same locally, add --threads=4 to a subset run, such as julia --threads=4 --project=test test/runtests.jl threads_only.
The AD workflow runs every backend on the current Julia release only. The AD versions workflow runs every Enzyme reverse and Mooncake reverse item on Julia 1.11 and 1.12, weekly and on demand. To run one of these locally, use julia +1.11 --project=test/ad test/ad/runtests.jl enzyme_reverse.
The Reactant support matrix in test/reactant/ runs weekly and on main, and fails when a cell's status differs from the committed results.tsv. It runs every AD registry scenario, forward and reverse, and the hand-written cases in cases.jl. Those cover what the registry cannot: a resumed call, a joined traced history, a call across 1,000 strata and the growth of compile time with the number of steps. They also hold a user's pure step, and change points and a sparse coupling built from traced values. A scenario Reactant cannot run is listed in the registry under the Reactant backend, with the cause. One whose traced call alone does not compile is listed under Reactant forward, and one whose gradient alone is wrong or does not compile under Reactant reverse. On pull requests that change src/ or ext/, a smoke run checks a few cases and scenarios against the same file. After a change, rerun it on Julia 1.12 from the repository root:
julia +1.12 --project=test/reactant -e 'using Pkg; Pkg.instantiate()'
julia +1.12 --project=test/reactant --startup-file=no test/reactant/runtests.jlThen commit results.tsv and RESULTS.md, and update expected.jl or the registry's Reactant lists. The environment resolves the current releases of Reactant, and RESULTS.md names the versions its results were recorded with. REACTANT_BACKENDS picks the backends that run, and REACTANT_RESULTS only names the results files. A run on another backend, such as a GPU, sets both: REACTANT_BACKENDS=gpu runs it, and REACTANT_RESULTS=gpu writes results-gpu.tsv and RESULTS-gpu.md, so it leaves the CPU results the weekly job compares against unchanged. The main tests check that the hand-written cases' rows agree with expected.jl, which lists CPU cells only; the Reactant workflow checks the registry rows against the registry.