Using DynamicHMC

Turing supports the use of DynamicHMC as a sampler through the DynamicNUTS function.

To use the DynamicNUTS function, you must import the DynamicHMC package as well as Turing. Turing does not formally require DynamicHMC but will include additional functionality if both packages are present.

Here is a brief example:

How to apply DynamicNUTS:

# Import Turing and DynamicHMC.
using DynamicHMC, Turing

# Model definition.
@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

# Pull 2,000 samples using DynamicNUTS.
dynamic_nuts = externalsampler(DynamicHMC.NUTS())
chn = sample(gdemo(1.5, 2.0), dynamic_nuts, 2000, progress=false)
╭─FlexiChain (2000 iterations, 1 chain) ───────────────────────────────────────
 ↓ iter  = 1:2000                                                             
 → chain = 1:1                                                                
                                                                              
 Parameters (2) ── AbstractPPL.VarName                                        
  Float64  s², m                                                              
                                                                              
 Extras (3)                                                                   
  Float64  logprior, loglikelihood, logjoint                                  
╰──────────────────────────────────────────────────────────────────────────────╯
Back to top