Skip to content

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.

julia
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 byMooncake reverseEnzyme reverseDecision
core recurrence (kernel, I or dense coupling)0.440.84keep
Depletion, hazard form0.160.31keep
Depletion, Floor(), dense coupling0.320.39keep
Depletion, Truncate(), dense coupling0.20³0.24³keep
Depletion, Truncate(κ), dense coupling0.20³0.32³keep
Depletion with two pools and a count flow0.280.40keep
Redistribute0.070.35keep
Depletion without a draw0.430.43keep
Depletion with two pools and waning0.400.32keep
Allocate0.32¹0.23¹keep
Allocate with imports and spill, 64 strata0.050.11keep
Depletion filled up to a capacity, flows before the draw0.260.32keep
Transform0.180.43keep
Primary() kernel0.510.66keep
Pairwise kernel0.20¹0.18¹keep
Pairwise routes, dense and sparse, 50 strata0.110.45keep
Diagonal coupling0.34¹0.48¹keep
sparse coupling0.29¹0.12¹keep
TimeVarying kernel and coupling0.29¹0.44¹keep
Convolution0.480.64keep
a sparse route coupling under plain ADplain AD0.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.

StepCaseMooncake reverseEnzyme reverseDecision
Hazardrenewal_depletion, 1 stratum0.971.00keep, for the empty pool
Hazardbvd_patch, 5 strata1.021.04keep, for the empty pool
Floorstrata_mixing, 5 strata0.981.03local derivative
Transform(clamp, lo, hi)renewal_clamp, 5 strata1.041.09local derivative
Truncatecapacity_beds, 20 strata1.171.22keep 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.

bash
julia benchmark/ab.jl --base=origin/main --cand=HEAD --rounds=3 \
    --targets=primal,ForwardDiff

The 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.

bash
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-results

The 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_CASES run a local arm, which hides the step_pullback of each modifier that has one, so the rule takes its local derivative.

  • The bvd_renewal, bvd_patches and bvd_delay cases time the model of the patch model case study, in the realistic and docs tiers. They add a loop arm, a hand loop in the style of the BVDOutbreakSize backend. They also add a handrule arm, the same loop with the hand-written Mooncake rules in benchmark/bvd_handrule.jl.

  • The cases in TUTORIAL_HANDRULE_CASES add a handrule arm beside their loop arm, with the rules in benchmark/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.

bash
task -t benchmark/Taskfile.yml matrix -- --tier=realistic --targets=primal
task -t benchmark/Taskfile.yml matrix -- --tier=realistic --targets=primal \
    --executor=threaded --threads=2,4

The 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, or 1e-4 for a scenario with single-precision parameters. Entries that are zero in exact arithmetic have an absolute floor of 1e-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| / h for a step h. Each entry is tried at a step relative to it and at a step of at least cbrt(eps()); a wrong reference misses by far more.

  • The rule testers that test_adjoint runs use a relative and absolute 1e-8, or 1e-3 in 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.

julia
("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_pullback or pullback! goes in test/unit, against a ForwardDiff Jacobian on small inputs. For a pure step, declare the step component of PieceInterface, which compares a step_pullback with the forward-mode pass. For a modifier step, depletion form or coupling, declare the pullback component of PieceInterface and test it with Interfaces.test(PieceInterface{(:pullback,)}, T, objs). For a whole call, use pullback_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 NoAdjoint twin, 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 on NoAdjoint itself 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_adjoint checks one registry operator of each kind of field and wrapper, listed in ADJOINT_SCENARIOS in test/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:

bash
julia +1.12 --project=test/reactant -e 'using Pkg; Pkg.instantiate()'
julia +1.12 --project=test/reactant --startup-file=no test/reactant/runtests.jl

Then 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.