AD tooling
The kit checks each package's gradients against a ForwardDiff reference on every supported AD backend, in CI. See Infrastructure and template sync for which files are managed and which the package owns.
Why test every backend
AD backends do not all agree. One can return a wrong gradient on a construct it mishandles while the model still evaluates and the sampler still runs. So every backend runs the same scenarios against the same reference, each as its own CI job. A scenario a backend cannot handle is recorded as broken rather than dropped.
Opting in
Pass ad = true to scaffold (the default for a numerical package). A tooling or non-numerical package passes ad = false.
scaffold(pkgdir(MyPackage); ad = true)This writes the AD CI caller, the test/ad/ harness, the ADFixtures registry skeleton and the AD test environment.
Files the kit scaffolds
test/ad/setup.jl(managed) wires the shared harness to the registry and exposestest_working_backendandtest_partial_backendas locals.test/ad/scenarios.jl(package-owned) has one starter@testitemper backend, tagged so CI can select one backend by tag.test/ad/runtests.jl(managed) discovers those items with TestItemRunner.test/ADFixtures/(package-owned) is the registry skeleton, with a placeholder scenario that runs out of the box.
The AD items have their own environment and CI, kept out of the main test run, because Enzyme, Mooncake and the rest are heavy dependencies.
Registering scenarios
Replace the placeholder scenario in test/ADFixtures/src/ADFixtures.jl with the package's own differentiable log densities. Add the backends the package supports to backends(). You can group scenarios by category, for example marginal and latent, and select a category from a test item. Each backend is its own @testitem in test/ad/scenarios.jl.
@testitem "ForwardDiff gradients (latent)" tags=[:ad, :forwarddiff] setup=[ADHelpers] begin
test_working_backend("ForwardDiff"; category = :latent)
endThe registry contract
The harness talks to a package's fixtures through the ADRegistry contract. A registry is any object, usually the package's ADFixtures module, that defines:
scenarios(; with_reference, kwargs...)returning the gradient scenarios, each with its function, input, contexts and ForwardDiff reference.backends()returning the backends to test as(; name, backend)named tuples.
Optional accessors, which default to empty:
broken_scenario_names()for scenarios broken on every backend.backend_broken_scenarios()for per-backend broken scenarios.backend_skip_scenarios()for per-backend scenarios too unstable to run at all.
A broken scenario still runs through check_broken, which asserts it fails, so a broken scenario that starts passing is flagged.
Gradient tolerance
By default a gradient must match its reference to rtol = 1e-6 and atol = 1e-6 (DEFAULT_GRADIENT_RTOL, DEFAULT_GRADIENT_ATOL). To change this, define the optional gradient_tolerance() accessor. It returns (; rtol, atol) for every backend, or a Dict from backend name to one.
gradient_tolerance() = Dict("Enzyme reverse" => (; rtol = 1e-4, atol = 1e-6))Loosen it only for the backend that needs it, with a comment saying why. The match is on the whole gradient vector, so a loose rtol lets one large coordinate hide a wrong small one.
Running AD tests locally
task test-adruns every backend in the AD environment.TAG=enzyme_reverse task test-ad-backendruns one backend by tag, as CI does.
Running one backend by tag is the fastest way to reproduce a CI failure that only one backend hits.
The backend matrix
The kit tests seven backends. ForwardDiff is also the reference the others are checked against.
| Backend | Package |
|---|---|
| ForwardDiff | ForwardDiff |
| ReverseDiff (tape) | ReverseDiff |
| ReverseDiff (compiled) | ReverseDiff |
| Enzyme forward | Enzyme |
| Enzyme reverse | Enzyme |
| Mooncake forward | Mooncake |
| Mooncake reverse | Mooncake |
One backend list drives everything
The list is defined once in the kit, in _AD_BACKENDS. It generates the README coverage-flag badge table, the codecov.yml per-backend flags, the coverage gate, the starter scenario test items, the AD dependencies in the harness, and the backends matrix the CI caller passes to the reusable workflow. The caller passes the matrix explicitly rather than using the reusable's default, so the CI matrix cannot drift from the badges and coverage flags. Change _AD_BACKENDS and all of these regenerate on the next sync.
The CI workflow and status badge
ad.yaml runs the per-backend matrix on pushes to main, pull requests and merge queues. It skips only AD-irrelevant changes such as prose docs. Each backend uploads coverage under its own flag, and the coverage gate waits until every flag has reported. The README has one AD status badge for the whole matrix, with a coverage badge per backend in the table below it.
Giving a slow backend more time
Raise the per-job timeout, in minutes, with ad_timeout.
using EpiAwarePackageTools
update("."; ad_timeout = 120)How ad_timeout is kept
It is written as timeout_minutes in the caller's with: block and kept by later syncs, so you pass it once. Leaving it unset writes no timeout_minutes, so the reusable workflow's default applies. Check first whether the job is slow or hanging, since a higher cap only stops it being killed.
Running the backends on another Julia version
The backends run on Julia 1. ad_julia_versions runs each backend on each listed version.
using EpiAwarePackageTools
update("."; ad_julia_versions = ["1", "lts"])Details and an alternative
The value is written as julia_versions in the caller's with: block and kept by later syncs. Coverage is uploaded from the first listed version only, so each per-backend flag gets one report. With more than one version, each job name ends with the version, for example ForwardDiff (Julia lts).
Alternatively, add a second caller of your own beside the managed ad.yaml, which syncs leave alone. Turn coverage off in it, so each flag still gets one report. Copy backends from the managed ad.yaml.
# .github/workflows/ad-lts.yaml
name: AD (Julia LTS)
on:
push:
branches: [main]
pull_request:
jobs:
ad:
uses: EpiAware/.github/.github/workflows/ad.yml@24fcf1ef918d135df4a0675f57db15f6d572fd66
with:
backends: '...'
julia-version: 'lts'
coverage: falseThe AD docs page
An ad = true package gets one managed page, AD comparison, in its Benchmarks nav group. It reports what each backend costs on the package's scenarios and has a short section on choosing a backend. Link to that section with @ref ad-backends.
The retired AD backends page
The separate AD backends page is retired and no longer carries the anchor. A sync deletes its source. It warns when the package-owned docs/docs_config.jl still registers it, since the sync cannot edit that file.
Where the page's numbers come from
The page reads the gradient timings the benchmark suite already published to the benchmarks branch. If there are none, it measures them during the docs build. You do not need to configure anything.
To read a different run, set AD_BENCHMARK_RESULTS in docs/docs_config.jl or as an environment variable.
# docs/docs_config.jl
const AD_BENCHMARK_RESULTS = "bench-results"AD_BENCHMARK_RESULTS=bench-results julia --project=docs docs/make.jlHow the numbers are found and shown
benchmark/benchmarks.jl builds its "AD gradients" group from the same test/ADFixtures registry the tests use, keyed ["AD gradients"][scenario][backend]. The pull request benchmark comment uses the same keys, so one suite feeds both. benchmark-history.yaml runs the suite on each push to main and deploys raw per-revision results to history/results/ on the benchmarks branch. latest.json there is the revision that run measured. The docs build resolves the branch with git, as the performance-history page does for history/table.md, so no checkout step is needed.
If the run has no gradient numbers, the docs build measures every (backend, scenario) pair itself. That is fine for a small registry but does not fit in a CI job for a large one.
AD_BENCHMARK_RESULTS names a results file or a directory of them. In a directory, latest.json wins, otherwise the most recently written file. A git checkout gives every file the same modification time, which is why the run names its own revision. A relative path resolves against docs/. The environment variable overrides the const, so CI can point at a checkout without editing the package-owned config.
When it reads results, the page renders what it finds and never measures:
Nothing found: the page says no measurements are available.
Some backends missing: the page renders those it has and names the rest. A gap means the suite does not cover that backend or names it differently from the registry. Both are package-owned and nothing checks that they agree.
Costs are relative to ForwardDiff where it has numbers, otherwise to the first backend that does. Each time is the fastest sample of its benchmark, the estimator DifferentiationInterfaceTest.benchmark_differentiation reports.
Making code AD-safe
This page is about testing that differentiable code works across backends. To make code differentiable in the first place, use EpiAwareADTools.jl. It holds the org's AD-safe evaluation hooks (cdf_ad_safe, primal and others) and AD workarounds, such as stripping an AD tape or giving a backend an analytic derivative for a cdf through SpecialFunctions.gamma_inc. A package imports it in its own source, and the scenarios registered here then test the result.
Note
The kit does not depend on EpiAwareADTools.jl. Each workaround there is documented against the upstream fix meant to replace it, and is deleted once that fix lands.