Automatic Differentiation

Switching AD Modes

Turing currently supports four automatic differentiation (AD) backends for sampling: ForwardDiff for forward-mode AD; and Mooncake, ReverseDiff, and Zygote for reverse-mode AD. ForwardDiff is automatically imported by Turing. To utilize Mooncake, Zygote, or ReverseDiff for AD, users must explicitly import them with import Mooncake, import Zygote or import ReverseDiff, alongside using Turing.

As of Turing version v0.30, the global configuration flag for the AD backend has been removed in favour of AdTypes.jl, allowing users to specify the AD backend for individual samplers independently. Users can pass the adtype keyword argument to the sampler constructor to select the desired AD backend, with the default being AutoForwardDiff(; chunksize=0).

For ForwardDiff, pass adtype=AutoForwardDiff(; chunksize) to the sampler constructor. A chunksize of nothing permits the chunk size to be automatically determined. For more information regarding the selection of chunksize, please refer to related section of ForwardDiff’s documentation.

For ReverseDiff, pass adtype=AutoReverseDiff() to the sampler constructor. An additional keyword argument called compile can be provided to AutoReverseDiff. It specifies whether to pre-record the tape only once and reuse it later (compile is set to false by default, which means no pre-recording). This can substantially improve performance, but risks silently incorrect results if not used with care.

Pre-recorded tapes should only be used if you are absolutely certain that the sequence of operations performed in your code does not change between different executions of your model.

Thus, e.g., in the model definition and all implicitly and explicitly called functions in the model, all loops should be of fixed size, and if-statements should consistently execute the same branches. For instance, if-statements with conditions that can be determined at compile time or conditions that depend only on fixed properties of the model, e.g. fixed data. However, if-statements that depend on the model parameters can take different branches during sampling; hence, the compiled tape might be incorrect. Thus you must not use compiled tapes when your model makes decisions based on the model parameters, and you should be careful if you compute functions of parameters that those functions do not have branching which might cause them to execute different code for different values of the parameter.

For Zygote, pass adtype=AutoZygote() to the sampler constructor.

And the previously used interface functions including ADBackend, setadbackend, setsafe, setchunksize, and setrdcache are deprecated and removed.

Compositional Sampling with Differing AD Modes

Turing supports intermixed automatic differentiation methods for different variable spaces. The snippet below shows using ForwardDiff to sample the mean (m) parameter, and using ReverseDiff for the variance (s) parameter:

using Turing
using ReverseDiff

# Define a simple Normal model with unknown mean and variance.
@model function gdemo(x, y)
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))
    x ~ Normal(m, sqrt(s²))
    return y ~ Normal(m, sqrt(s²))
end

# Sample using Gibbs and varying autodiff backends.
c = sample(
    gdemo(1.5, 2),
    Gibbs(
        HMC(0.1, 5, :m; adtype=AutoForwardDiff(; chunksize=0)),
        HMC(0.1, 5, :s²; adtype=AutoReverseDiff(false)),
    ),
    1000,
    progress=false,
)
Chains MCMC chain (1000×3×1 Array{Float64, 3}):

Iterations        = 1:1:1000
Number of chains  = 1
Samples per chain = 1000
Wall duration     = 9.86 seconds
Compute duration  = 9.86 seconds
parameters        = s², m
internals         = lp

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e ⋯
      Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

          s²    2.1337    2.2314    0.1574   211.1154   272.3584    1.0016     ⋯
           m    1.2368    0.7748    0.0759   106.5374   149.3865    1.0026     ⋯
                                                                1 column omitted

Quantiles
  parameters      2.5%     25.0%     50.0%     75.0%     97.5%
      Symbol   Float64   Float64   Float64   Float64   Float64

          s²    0.6189    1.0877    1.5694    2.3574    7.2249
           m   -0.4003    0.7643    1.2570    1.7158    2.7053

Generally, reverse-mode AD, for instance ReverseDiff, is faster when sampling from variables of high dimensionality (greater than 20), while forward-mode AD, for instance ForwardDiff, is more efficient for lower-dimension variables. This functionality allows those who are performance sensitive to fine tune their automatic differentiation for their specific models.

If the differentiation method is not specified in this way, Turing will default to using whatever the global AD backend is. Currently, this defaults to ForwardDiff.

The most reliable way to ensure you are using the fastest AD that works for your problem is to benchmark them using TuringBenchmarking:

using TuringBenchmarking
benchmark_model(gdemo(1.5, 2), adbackends=[AutoForwardDiff(), AutoReverseDiff()])
2-element BenchmarkTools.BenchmarkGroup:
  tags: []
  "evaluation" => 2-element BenchmarkTools.BenchmarkGroup:
      tags: []
      "linked" => Trial(430.000 ns)
      "standard" => Trial(330.000 ns)
  "gradient" => 2-element BenchmarkTools.BenchmarkGroup:
      tags: []
      "ADTypes.AutoReverseDiff()" => 2-element BenchmarkTools.BenchmarkGroup:
          tags: ["ReverseDiff"]
          "linked" => Trial(15.329 μs)
          "standard" => Trial(13.496 μs)
      "ADTypes.AutoForwardDiff()" => 2-element BenchmarkTools.BenchmarkGroup:
          tags: ["ForwardDiff"]
          "linked" => Trial(601.000 ns)
          "standard" => Trial(490.000 ns)
Back to top