Git Product home page Git Product logo

advancedhmc.jl's Introduction

AdvancedHMC.jl

CI DOI Coverage Status Stable Dev

AdvancedHMC.jl provides a robust, modular, and efficient implementation of advanced HMC algorithms. An illustrative example of AdvancedHMC's usage is given below. AdvancedHMC.jl is part of Turing.jl, a probabilistic programming library in Julia. If you are interested in using AdvancedHMC.jl through a probabilistic programming language, please check it out!

Interfaces

  • IMP.hmc: an experimental Python module for the Integrative Modeling Platform, which uses AdvancedHMC in its backend to sample protein structures.

NEWS

  • We presented a paper for AdvancedHMC.jl at AABI in 2019 in Vancouver, Canada. (abs, pdf, OpenReview)
  • We presented a poster for AdvancedHMC.jl at StanCon 2019 in Cambridge, UK. (pdf)

API CHANGES

  • [v0.5.0] Breaking! Convenience constructors for common samplers changed to:
    • HMC(leapfrog_stepsize::Real, n_leapfrog::Int)
    • NUTS(target_acceptance::Real)
    • HMCDA(target_acceptance::Real, integration_time::Real)
  • [v0.2.22] Three functions are renamed.
    • Preconditioner(metric::AbstractMetric) -> MassMatrixAdaptor(metric) and
    • NesterovDualAveraging(δ, integrator::AbstractIntegrator) -> StepSizeAdaptor(δ, integrator)
    • find_good_eps -> find_good_stepsize
  • [v0.2.15] n_adapts is no longer needed to construct StanHMCAdaptor; the old constructor is deprecated.
  • [v0.2.8] Two Hamiltonian trajectory sampling methods are renamed to avoid a name clash with Distributions.
    • Multinomial -> MultinomialTS
    • Slice -> SliceTS
  • [v0.2.0] The gradient function passed to Hamiltonian is supposed to return a value-gradient tuple now.

A minimal example - sampling from a multivariate Gaussian using NUTS

This section demonstrates a minimal example of sampling from a multivariate Gaussian (10-dimensional) using the no U-turn sampler (NUTS). Below we describe the major components of the Hamiltonian system which are essential to sample using this approach:

  • Metric: In many sampling problems the sample space is associated with a metric that allows us to measure the distance between any two points, and other similar quantities. In the example in this section, we use a special metric called the Euclidean Metric, represented with a D × D matrix from which we can compute distances.1

  • Leapfrog integration: Leapfrog integration is a second-order numerical method for integrating differential equations (In this case they are equations of motion for the relative position of one particle with respect to the other). The order of this integration signifies its rate of convergence. Any algorithm with a finite time step size will have numerical errors, and the order is related to this error. For a second-order algorithm, this error scales as the second power of the time step, hence, the name second-order. High-order integrators are usually complex to code and have a limited region of convergence; hence they do not allow arbitrarily large time steps. A second-order integrator is suitable for our purpose. Hence we opt for the leapfrog integrator. It is called leapfrog due to the ways this algorithm is written, where the positions and velocities of particles "leap over" each other.2

  • Kernel for trajectories (static or dynamic): Different kernels, which may be static or dynamic, can be used. At each iteration of any variant of the HMC algorithm, there are two main steps - the first step changes the momentum and the second step may change both the position and the momentum of a particle.3

using AdvancedHMC, ForwardDiff
using LogDensityProblems
using LinearAlgebra

# Define the target distribution using the `LogDensityProblem` interface
struct LogTargetDensity
    dim::Int
end
LogDensityProblems.logdensity(p::LogTargetDensity, θ) = -sum(abs2, θ) / 2  # standard multivariate normal
LogDensityProblems.dimension(p::LogTargetDensity) = p.dim
LogDensityProblems.capabilities(::Type{LogTargetDensity}) = LogDensityProblems.LogDensityOrder{0}()

# Choose parameter dimensionality and initial parameter value
D = 10; initial_θ = rand(D)
ℓπ = LogTargetDensity(D)

# Set the number of samples to draw and warmup iterations
n_samples, n_adapts = 2_000, 1_000

# Define a Hamiltonian system
metric = DiagEuclideanMetric(D)
hamiltonian = Hamiltonian(metric, ℓπ, ForwardDiff)

# Define a leapfrog solver, with the initial step size chosen heuristically
initial_ϵ = find_good_stepsize(hamiltonian, initial_θ)
integrator = Leapfrog(initial_ϵ)

# Define an HMC sampler with the following components
#   - multinomial sampling scheme,
#   - generalised No-U-Turn criteria, and
#   - windowed adaption for step-size and diagonal mass matrix
kernel = HMCKernel(Trajectory{MultinomialTS}(integrator, GeneralisedNoUTurn()))
adaptor = StanHMCAdaptor(MassMatrixAdaptor(metric), StepSizeAdaptor(0.8, integrator))

# Run the sampler to draw samples from the specified Gaussian, where
#   - `samples` will store the samples
#   - `stats` will store diagnostic statistics for each sample
samples, stats = sample(hamiltonian, kernel, initial_θ, n_samples, adaptor, n_adapts; progress=true)

Parallel sampling

AdvancedHMC enables parallel sampling (either distributed or multi-thread) via Julia's parallel computing functions. It also supports vectorized sampling for static HMC.

The below example utilizes the @threads macro to sample 4 chains across 4 threads.

# Ensure that Julia was launched with an appropriate number of threads
println(Threads.nthreads())

# Number of chains to sample
nchains = 4

# Cache to store the chains
chains = Vector{Any}(undef, nchains)

# The `samples` from each parallel chain is stored in the `chains` vector 
# Adjust the `verbose` flag as per need
Threads.@threads for i in 1:nchains
  samples, stats = sample(hamiltonian, kernel, initial_θ, n_samples, adaptor, n_adapts; verbose=false)
  chains[i] = samples
end

Using the AbstractMCMC interface

Users can also use the AbstractMCMC interface to sample, which is also used in Turing.jl. In order to show how this is done let us start from our previous example where we defined a LogTargetDensity, ℓπ.

using AbstractMCMC, LogDensityProblemsAD
# Wrap the previous LogTargetDensity as LogDensityModel 
# where ℓπ::LogTargetDensity
model = AdvancedHMC.LogDensityModel(LogDensityProblemsAD.ADgradient(Val(:ForwardDiff), ℓπ))

# Wrap the previous sampler as a HMCSampler <: AbstractMCMC.AbstractSampler
D = 10; initial_θ = rand(D)
n_samples, n_adapts, δ = 1_000, 2_000, 0.8
sampler = HMCSampler(kernel, metric, adaptor) 

# Now sample
samples = AbstractMCMC.sample(
      model,
      sampler,
      n_adapts + n_samples;
      nadapts = n_adapts,
      initial_params = initial_θ,
  )

Convenience Constructors

In the previous examples, we built the sampler by manually specifying the integrator, metric, kernel, and adaptor to build our own sampler. However, in many cases, users might want to initialize a standard NUTS sampler. In such cases having to define each of these aspects manually is tedious and error-prone. For these reasons AdvancedHMC also provides users with a series of convenience constructors for standard samplers. We will now show how to use them.

  • HMC:

    # HMC Sampler
    # step size, number of leapfrog steps 
    n_leapfrog, ϵ = 25, 0.1
    hmc = HMC(ϵ, n_leapfrog)

    Equivalent to:

    metric = DiagEuclideanMetric(D)
    hamiltonian = Hamiltonian(metric, ℓπ, ForwardDiff)
    integrator = Leapfrog(0.1)
    kernel = HMCKernel(Trajectory{EndPointTS}(integrator, FixedNSteps(n_leapfrog)))
    adaptor = NoAdaptation()
    hmc = HMCSampler(kernel, metric, adaptor)
  • NUTS:

    # NUTS Sampler
    # adaptation steps, target acceptance probability,
    δ = 0.8
    nuts = NUTS(δ)

    Equivalent to:

    metric = DiagEuclideanMetric(D)
    hamiltonian = Hamiltonian(metric, ℓπ, ForwardDiff)
    initial_ϵ = find_good_stepsize(hamiltonian, initial_θ)
    integrator = Leapfrog(initial_ϵ)
    kernel =  HMCKernel(Trajectory{MultinomialTS}(integrator, GeneralisedNoUTurn()))
    adaptor = StanHMCAdaptor(MassMatrixAdaptor(metric), StepSizeAdaptor(δ, integrator))
    nuts = HMCSampler(kernel, metric, adaptor)
  • HMCDA:

    #HMCDA (dual averaging)
    # adaptation steps, target acceptance probability, target trajectory length 
    δ, λ = 0.8, 1.0
    hmcda = HMCDA(δ, λ)

    Equivalent to:

    metric = DiagEuclideanMetric(D)
    hamiltonian = Hamiltonian(metric, ℓπ, ForwardDiff)
    initial_ϵ = find_good_stepsize(hamiltonian, initial_θ)
    integrator = Leapfrog(initial_ϵ)
    kernel = HMCKernel(Trajectory{EndPointTS}(integrator, FixedIntegrationTime(λ)))
    adaptor = StepSizeAdaptor(δ, initial_ϵ)
    hmcda = HMCSampler(kernel, metric, adaptor)

Moreover, there's some flexibility in how these samplers can be initialized. For example, a user can initialize a NUTS (HMC and HMCDA) sampler with their own metrics and integrators. This can be done as follows:

nuts = NUTS(δ, metric = :diagonal) #metric = DiagEuclideanMetric(D) (Default!)
nuts = NUTS(δ, metric = :unit)     #metric = UnitEuclideanMetric(D)
nuts = NUTS(δ, metric = :dense)    #metric = DenseEuclideanMetric(D)
# Provide your own AbstractMetric
metric = DiagEuclideanMetric(10)
nuts = NUTS(δ, metric = metric)

nuts = NUTS(δ, integrator = :leapfrog)         #integrator = Leapfrog(ϵ) (Default!)
nuts = NUTS(δ, integrator = :jitteredleapfrog) #integrator = JitteredLeapfrog(ϵ, 0.1ϵ)
nuts = NUTS(δ, integrator = :temperedleapfrog) #integrator = TemperedLeapfrog(ϵ, 1.0)

# Provide your own AbstractIntegrator
integrator = JitteredLeapfrog(0.1, 0.2)
nuts = NUTS(δ, integrator = integrator) 

GPU Sampling with CUDA

There is experimental support for running static HMC on the GPU using CUDA. To do so, the user needs to have CUDA.jl installed, ensure the logdensity of the Hamiltonian can be executed on the GPU and that the initial points are a CuArray. A small working example can be found at test/cuda.jl.

API and supported HMC algorithms

An important design goal of AdvancedHMC.jl is modularity; we would like to support algorithmic research on HMC. This modularity means that different HMC variants can be easily constructed by composing various components, such as preconditioning metric (i.e., mass matrix), leapfrog integrators, trajectories (static or dynamic), adaption schemes, etc. The minimal example above can be modified to suit particular inference problems by picking components from the list below.

Hamiltonian mass matrix (metric)

  • Unit metric: UnitEuclideanMetric(dim)
  • Diagonal metric: DiagEuclideanMetric(dim)
  • Dense metric: DenseEuclideanMetric(dim)

where dim is the dimensionality of the sampling space.

Integrator (integrator)

  • Ordinary leapfrog integrator: Leapfrog(ϵ)
  • Jittered leapfrog integrator with jitter rate n: JitteredLeapfrog(ϵ, n)
  • Tempered leapfrog integrator with tempering rate a: TemperedLeapfrog(ϵ, a)

where ϵ is the step size of leapfrog integration.

Kernel (kernel)

  • Static HMC with a fixed number of steps (n_steps) (Neal, R. M. (2011)): HMCKernel(Trajectory{EndPointTS}(integrator, FixedNSteps(integrator)))
  • HMC with a fixed total trajectory length (trajectory_length) (Neal, R. M. (2011)): HMCKernel(Trajectory{EndPointTS}(integrator, FixedIntegrationTime(trajectory_length)))
  • Original NUTS with slice sampling (Hoffman, M. D., & Gelman, A. (2014)): HMCKernel(Trajectory{SliceTS}(integrator, ClassicNoUTurn()))
  • Generalised NUTS with slice sampling (Betancourt, M. (2017)): HMCKernel(Trajectory{SliceTS}(integrator, GeneralisedNoUTurn()))
  • Original NUTS with multinomial sampling (Betancourt, M. (2017)): HMCKernel(Trajectory{MultinomialTS}(integrator, ClassicNoUTurn()))
  • Generalised NUTS with multinomial sampling (Betancourt, M. (2017)): HMCKernel(Trajectory{MultinomialTS}(integrator, GeneralisedNoUTurn()))

Adaptor (adaptor)

  • Adapt the mass matrix metric of the Hamiltonian dynamics: mma = MassMatrixAdaptor(metric)
    • This is lowered to UnitMassMatrix, WelfordVar or WelfordCov based on the type of the mass matrix metric
  • Adapt the step size of the leapfrog integrator integrator: ssa = StepSizeAdaptor(δ, integrator)
    • It uses Nesterov's dual averaging with δ as the target acceptance rate.
  • Combine the two above naively: NaiveHMCAdaptor(mma, ssa)
  • Combine the first two using Stan's windowed adaptation: StanHMCAdaptor(mma, ssa)

Gradients

AdvancedHMC supports AD-based using LogDensityProblemsAD and user-specified gradients. In order to use user-specified gradients, please replace ForwardDiff with ℓπ_grad in the Hamiltonian constructor, where the gradient function ℓπ_grad should return a tuple containing both the log-posterior and its gradient.

All the combinations are tested in this file except for using tempered leapfrog integrator together with adaptation, which we found unstable empirically.

The sample function signature in detail

function sample(
    rng::Union{AbstractRNG, AbstractVector{<:AbstractRNG}},
    h::Hamiltonian,
    κ::HMCKernel,
    θ::AbstractVector{<:AbstractFloat},
    n_samples::Int,
    adaptor::AbstractAdaptor=NoAdaptation(),
    n_adapts::Int=min(div(n_samples, 10), 1_000);
    drop_warmup=false,
    verbose::Bool=true,
    progress::Bool=false,
)

Draw n_samples samples using the kernel κ under the Hamiltonian system h

  • The randomness is controlled by rng.
    • If rng is not provided, GLOBAL_RNG will be used.
  • The initial point is given by θ.
  • The adaptor is set by adaptor, for which the default is no adaptation.
    • It will perform n_adapts steps of adaptation, for which the default is 1_000 or 10% of n_samples, whichever is lower.
  • drop_warmup specifies whether to drop samples.
  • verbose controls the verbosity.
  • progress controls whether to show the progress meter or not.

Note that the function signature of the sample function exported by AdvancedHMC.jl differs from the sample function used by Turing.jl. We refer to the documentation of Turing.jl for more details on the latter.

Citing AdvancedHMC.jl

If you use AdvancedHMC.jl for your own research, please consider citing the following publication:

Kai Xu, Hong Ge, Will Tebbutt, Mohamed Tarek, Martin Trapp, Zoubin Ghahramani: "AdvancedHMC.jl: A robust, modular and efficient implementation of advanced HMC algorithms.", Symposium on Advances in Approximate Bayesian Inference, 2020. (abs, pdf)

with the following BibTeX entry:

@inproceedings{xu2020advancedhmc,
  title={AdvancedHMC. jl: A robust, modular and efficient implementation of advanced HMC algorithms},
  author={Xu, Kai and Ge, Hong and Tebbutt, Will and Tarek, Mohamed and Trapp, Martin and Ghahramani, Zoubin},
  booktitle={Symposium on Advances in Approximate Bayesian Inference},
  pages={1--10},
  year={2020},
  organization={PMLR}
}

If you using AdvancedHMC.jl directly through Turing.jl, please consider citing the following publication:

Hong Ge, Kai Xu, and Zoubin Ghahramani: "Turing: a language for flexible probabilistic inference.", International Conference on Artificial Intelligence and Statistics, 2018. (abs, pdf)

with the following BibTeX entry:

@inproceedings{ge2018turing,
  title={Turing: A language for flexible probabilistic inference},
  author={Ge, Hong and Xu, Kai and Ghahramani, Zoubin},
  booktitle={International Conference on Artificial Intelligence and Statistics},
  pages={1682--1690},
  year={2018},
  organization={PMLR}
}

References

  1. Neal, R. M. (2011). MCMC using Hamiltonian dynamics. Handbook of Markov chain Monte Carlo, 2(11), 2. (arXiv)

  2. Betancourt, M. (2017). A Conceptual Introduction to Hamiltonian Monte Carlo. arXiv preprint arXiv:1701.02434.

  3. Girolami, M., & Calderhead, B. (2011). Riemann manifold Langevin and Hamiltonian Monte Carlo methods. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 73(2), 123-214. (arXiv)

  4. Betancourt, M. J., Byrne, S., & Girolami, M. (2014). Optimizing the integrator step size for Hamiltonian Monte Carlo. arXiv preprint arXiv:1411.6669.

  5. Betancourt, M. (2016). Identifying the optimal integration time in Hamiltonian Monte Carlo. arXiv preprint arXiv:1601.00225.

  6. Hoffman, M. D., & Gelman, A. (2014). The No-U-Turn Sampler: adaptively setting path lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(1), 1593-1623. (arXiv)

Footnotes

Footnotes

  1. The Euclidean metric is also known as the mass matrix in the physical perspective. See Hamiltonian mass matrix for available metrics.

  2. About the leapfrog integration scheme: Suppose ${\bf x}$ and ${\bf v}$ are the position and velocity of an individual particle respectively; $i$ and $i+1$ are the indices for time values $t_i$ and $t_{i+1}$ respectively; $dt = t_{i+1} - t_i$ is the time step size (constant and regularly spaced intervals), and ${\bf a}$ is the acceleration induced on a particle by the forces of all other particles. Furthermore, suppose positions are defined at times $t_i, t_{i+1}, t_{i+2}, \dots $, spaced at constant intervals $dt$, the velocities are defined at halfway times in between, denoted by $t_{i-1/2}, t_{i+1/2}, t_{i+3/2}, \dots $, where $t_{i+1} - t_{i + 1/2} = t_{i + 1/2} - t_i = dt / 2$, and the accelerations ${\bf a}$ are defined only on integer times, just like the positions. Then the leapfrog integration scheme is given as: $x_{i} = x_{i-1} + v_{i-1/2} dt; \quad v_{i+1/2} = v_{i-1/2} + a_i dt$. For available integrators refer to Integrator.

  3. On kernels: In the classical HMC approach, during the first step, new values for the momentum variables are randomly drawn from their Gaussian distribution, independently of the current values of the position variables. A Metropolis update is performed during the second step, using Hamiltonian dynamics to provide a new state. For available kernels refer to Kernel.

advancedhmc.jl's People

Contributors

andreasnoack avatar chriselrod avatar chrisrackauckas avatar cpfiffer avatar cscherrer avatar devmotion avatar ebb-earl-co avatar github-actions[bot] avatar ivanyashchuk avatar jaimerzp avatar jeetsuthar avatar juliatagbot avatar kaandocal avatar mhauru avatar mohamed82008 avatar rhaps0dy avatar saranjeetkaur avatar scheidan avatar sethaxen avatar shravanngoswamii avatar simeonschaub avatar theogf avatar torfjelde avatar trappmartin avatar treigerm avatar vaibhavdixit02 avatar willtebbutt avatar xukai92 avatar yebai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

advancedhmc.jl's Issues

Samples during adaption phase

Maybe we should make the sample function not return those samples by default (and support an optional keyword for it)?

Update repo description

@yebai It seems that I don't have access to edit the description of the repo after the transfer. Maybe we want something like "Efficient building blocks for modern HMC samplers"?

DynamicHMC is (~5 times) faster than Turing's HMC implementation

Time used for collecting 2 million samples

  • Turing.NUTS: 3318.293540 seconds (33.35 G allocations: 1.299 TiB, 29.35% gc time)
  • Turing.DynamicNUTS: 848.741643 seconds (7.86 G allocations: 251.076 GiB, 32.13% gc time)

using the following

using DynamicHMC, Turing, Test

@model gdemo(x, y) = begin
  s ~ InverseGamma(2,3)
  m ~ Normal(0,sqrt(s))
  x ~ Normal(m, sqrt(s))
  y ~ Normal(m, sqrt(s))
  return s, m
end

mf = gdemo(1.5, 2.0)

@time chn1 = sample(mf, DynamicNUTS(2000000));

@time chn2 = sample(mf, Turing.NUTS(2000000, 0.65));

Add more informative error messages.

I just came across the error message at:

@warn "The current proposal will be rejected (due to numerical error(s))..."

This error message should be more informative so that the user gets an idea why he gets it, i.e. in my case I suppose the model I'm looking at is misspecified. It would be good to know what is Inf.

Simplifying `Metric` types by using `AbstractPDMat`

The following 3 types in src/metric.jl:

  • struct DiagEuclideanMetric{T<:Real,A<:AbstractVector{T}} <: AbstractMetric{T}
    dim :: Int
    # Diagnal of the inverse of the mass matrix
    M⁻¹ :: A
    # Sqare root of the inverse of the mass matrix
    sqrtM⁻¹ :: A
    # Pre-allocation for intermediate variables
    _temp :: A
    end

  • struct DenseEuclideanMetric{T<:Real,AV<:AbstractVector{T},AM<:AbstractMatrix{T}} <: AbstractMetric{T}
    dim :: Int
    # Inverse of the mass matrix
    M⁻¹ :: AM
    # U of the Cholesky decomposition of the mass matrix
    cholM⁻¹ :: UpperTriangular{T,AM}
    # Pre-allocation for intermediate variables
    _temp :: AV
    end

  • struct UnitEuclideanMetric{T<:Real} <: AbstractMetric{T}
    dim :: Int
    end

can be merged into one type using AbstractPDMat

struct EuclideanMetric{T<:Real,A<:AbstractPDMat{T}} <: AbstractMetric{T}
    M⁻¹     ::  A # contains dim, M⁻¹ and its Cholesky decomposition. 
    # Pre-allocation for intermediate variables
    _temp   ::  A
end

Reference: https://github.com/JuliaStats/PDMats.jl

RFC `find_good_eps`

Copied from @yebai comment in #23 (comment)

    r = rand_momentum(rng, h)
    H = hamiltonian_energy(h, θ, r)

out of find_good_eps and wraping

        θ′, r′, _is_valid = step(Leapfrog(ϵ′), h, θ′, r′)
        H_new = _is_valid ? hamiltonian_energy(h, θ′, r′) : Inf

into a function

function A(ϵ, h, θ, r) 
        θ′, r′, _is_valid = step(Leapfrog(ϵ′), h, θ′, r′)
        return H_new = _is_valid ? hamiltonian_energy(h, θ′, r′) : Inf
end

Then, we can drop the dependency on AdvancedHMC from this function: find_good_eps(h::Hamiltonian, θ::AbstractVector{T}, A::Function; max_n_iters::Int=100), and move it into adaption/stepsize.jl.

More robust and modular way of detecting divergence

Approximation error of leapfrog integration (i.e. accumulated Hamiltonian energy error) can sometimes explode, for example when the curvature of the current region is very high. This type of approximation error is sometimes called divergence [1] since it shifts a leapfrog simulation away from the correct solution.

In Turing, this type of errors is currently caught a relatively ad-hoc function called is_valid ,

function is_valid(v::AbstractVector{<:Real})

is_valid can catch cases where one or more elements of the parameter vector is either nan or inf. This has several drawbacks

  • it's not general enough for catching all leapfrog approximation errors, e.g. when the parameter vector is valid but Hamiltonian energy is invalid.
  • it may be delayed because numerical errors can appear in Hamiltonian energy earlier than in parameter vectors
  • it's hard to propagate the exception around, i.e. at the moment we use a heuristic to find the previous valid point before approximation/numerical error happens

Therefore, we might want to refactor the current code a bit for a more robust mechanism for handling leapfrog approximation errors. Perhaps we can learn from the DynamicHMC implementation:

https://github.com/tpapp/DynamicHMC.jl/blob/master/src/buildingblocks.jl#L168

[1]: Betancourt, M. (2017). A Conceptual Introduction to Hamiltonian Monte Carlo. arXiv preprint arXiv:1701.02434.

Identify divergent transition

I was speaking with Kai about this and agreed it would be good to be able to identify divergence of a particular transition (Sec. 6.2 in here ) allowing us to identify pathologies which may bias the posterior sample.

Related papers

Neal, R. M. (2011). MCMC using Hamiltonian dynamics. Handbook of Markov chain Monte Carlo, 2(11), 2. (pdf)

Betancourt, M. (2017). A Conceptual Introduction to Hamiltonian Monte Carlo. arXiv preprint arXiv:1701.02434.

Girolami, M., & Calderhead, B. (2011). Riemann manifold Langevin and Hamiltonian Monte Carlo methods. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 73(2), 123-214. (link)

Betancourt, M. J., Byrne, S., & Girolami, M. (2014). Optimizing the integrator step size for Hamiltonian Monte Carlo. arXiv preprint arXiv:1411.6669.

Betancourt, M. (2016). Identifying the optimal integration time in Hamiltonian Monte Carlo. arXiv preprint arXiv:1601.00225.

Hoffman, M. D., & Gelman, A. (2014). The No-U-Turn Sampler: adaptively setting path lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(1), 1593-1623.

License?

Hi @xukai92, I'd like to start a repository heavily based on your code, but with some modifications that lead to incompatibility. I don't see a license file. Is there one you prefer? I'd like to use MIT or BSD if possible. Thanks!

sample in this package and Distributions

Both this package and Distributions.jl define a sample function, as opposed to this package extending Distributions.jl's sample function with new methods. This causes a name clash which, given that these packages will likely be used to together a lot, is annoying. Should we maybe extend Distributions.jl's sample rather than define our own?

Hong's abstraction draft for unifying trajectories from PR #69

Moved from #69

#################################
### Hong's abstraction starts ###
#################################

###
### Create a `Termination` type for each `Trajectory` type, e.g. HMC, NUTS etc.
### Merge all `Trajectory` types, and make `transition` dispatch on `Termination`,
### such that we can overload `transition` for different HMC samplers.
### NOTE:  stopping creteria, max_depth::Int, Δ_max::AbstractFloat, n_steps, λ
###

"""
Abstract type for termination.
"""
abstract type AbstractTermination end

# Termination type for HMC and HMCDA
struct StaticTermination{D<:AbstractFloat} <: AbstractTermination
    n_steps :: Int
    Δ_max :: D
end

# NoUTurnTermination
struct NoUTurnTermination{D<:AbstractFloat} <: AbstractTermination
    max_depth :: Int
    Δ_max :: D
    # TODO: add other necessary fields for No-U-Turn stopping creteria.
end

struct Trajectory{I<:AbstractIntegrator} <: AbstractTrajectory{I}
    integrator :: I
    n_steps :: Int # Counter for total leapfrog steps already applied.
    Δ :: AbstractFloat # Current hamiltonian energy minus starting hamiltonian energy
    # TODO: replace all ``*Trajectory` types with `Trajectory`.
    # TODO: add turn statistic, divergent statistic, proposal statistic
end

isterminated(
    x::StaticTermination,
    τ::Trajectory
) = τ.n_steps >= x.n_steps || τ.Δ >= x.Δ_max

# Combine trajectories, e.g. those created by the build_tree algorithm.
#  NOTE: combine proposal (via slice/multinomial sampling), combine turn statistic,
#       and combine divergent statistic.
combine_trajectory(τ′::Trajectory, τ′′::Trajectory) = nothing # To-be-implemented.

## TODO: move slice variable `logu` into `Trajectory`?
combine_proposal(τ′::Trajectory, τ′′::Trajectory) = nothing # To-be-implemented.
combine_turn(τ′::Trajectory, τ′′::Trajectory) = nothing # To-be-implemented.
combine_divergence(τ′::Trajectory, τ′′::Trajectory) = nothing # To-be-implemented.

transition(
    τ::Trajectory{I},
    h::Hamiltonian,
    z::PhasePoint,
    t::T
) where {I<:AbstractIntegrator,T<:AbstractTermination} = nothing

###############################
### Hong's abstraction ends ###
###############################

RFC `Adapter` types

Copied from @yebai's comments in #23 (comment)

can we

  • move this file's content into adaptation/Adaptation.jl
  • remove the file src/adaptation.jl
  • and include adaptation/Adaptation.jl from AdvancedHMC directly?

Copied from @yebai's comments in #23 (comment)

consider merging the following three functions

  • getss(fss::FixedStepSize)
  • getss(da::DualAveraging)
  • getss(mssa::ManualSSAdapter)

into

  • getϵ(a:: StepSizeAdapter) = a.ϵ, or more generally
  • getϵ(a:: AbstractAdapter) = a.ϵ

Copied from @yebai's comments in #23 (comment)

consider removing ManualSSAdapter and related code, since we can always use FixedStepSize

Copied from @yebai's comments in #23 (comment)

can we make DualAveraging an immutable type, and let

  • adapt_stepsize!, adapt!
  • finalize!

always return a new DualAveraging instance. This can improve both readability and performance since immutable types are allocated on stacks. If so, we can also remove

  • reset!

and merge

  • adapt!(da::DualAveraging, θ::AbstractVector{<:AbstractFloat}, α::AbstractFloat)
  • adapt_stepsize!(da::DualAveraging, α::AbstractFloat)

into

-adapt(d::AbstractAdaptor, α::AbstractFloat=1.0, θ::AbstractVector{<:AbstractFloat}=zeros(0))

We can probably do similar things for Metric adaptors.

Copied from @yebai's comments in #23 (comment)

Consider

  • removing `AbstractCompositeAdapter, and
  • making NaiveCompAdaptor and ThreePhaseAdaptor direct subtypes of AbstractAdapter

Since AbstractCompositeAdapter is only used to define

  • getM⁻¹(ca::AbstractCompositeAdapter)
  • getss(ca::AbstractCompositeAdapter)
  • update(h::Hamiltonian, p::AbstractProposal, a::Adaptation.AbstractCompositeAdapter)

These functions can be defined for AbstractAdaptor directly:

  • getM⁻¹(a::AbstractAdapter) = a.var
  • getss(a::AbstractAdapter) = a.ϵ
  • update(h::Hamiltonian, p::AbstractProposal, a::Adaptation.AbstractCompositeAdapter)

Then we can overload these functions for subtypes of AbstractAdaptor

  • getM⁻¹(a:: ThreePhaseAdapter) = getM⁻¹(a.pc)
  • getss(a:: ThreePhaseAdapter) = getss(a.ssa)
  • getM⁻¹(dpc::UnitPreConditioner) = nothing (perhaps return 1.0 instead of nothing)
  • getM⁻¹(dpc::DensePreConditioner) = dpc.covar

[RFC]: notations used in this package

At the moment, we are using the following notations:

  • logπ - log target distribution
  • ∂logπ∂θ - gradient
  • prop - transitioning kernel
  • θ_init - initial value for sampling states / parameters

I think this can be improved by

  • ∂logπ∂θ ==> ∇logπ
  • prop ==> κ (kappa) or τ (tau) - MH transitioning kernel
  • θ - parameters, r - momentum
  • θ_init ==> θ₀ (theta_{0}), r_init ==> r₀ (r_{0})
  • z := (θ, r) - (position, momentum) pair

Any other notations missing?

Instantiation of new `AbstractMetric`s

We currently have a method for each AbstractMetric which enables us to make another instance of the metric of the following form:

metric = ...
new_metric_of_same_type = metric(inverse_mass_matrix)

Why do we need such a method?

Correctly testing show functions

Currently during test the verbosity is disable for clean test output thus show() functions are not tests at all. We may want to include tests for the explicitly.

Possible (algorithmic) speedups

  1. avoiding running unnecessary pass of the pdf function of the target distribution
  • the current design separates the pdf and its gradient and there are some duplicated evaluation of the pdf
  1. update is doing unnecessary decomposition of matrix (#24)
  • need to have a flag to indicate if M inverse is update by adaptor

Support mutable and immutable array types

Discussions in #5 (comment)

@mohamed82008 I reverted some functions about pre-allocating memory so that only intermediate variables are pre-allocated and all functions remains immutable. This is to avoid un-expected behaviour due to mutability. We probably want to implement mutable version of functions to pre-allocate memory for return variables explicitly later. Does it sound good to you?

Sorry, I missed this question. I think it would be nice to support mutable and immutable array types, e.g. StaticArrays.SArray and StaticArrays.MArray or Vector. I saw Chris mention somewhere that DiffEq does this by defining 2 versions of the function, one for mutable arrays and one for immutable. We might want to explore something like this in a future PR. The mutating version takes a first argument the pre-allocated output vector whereas the non-mutating version doesn't. Supporting StaticArrays would be an interesting direction to pursue to gain some speedup for parameter vectors of size <1000 or so. Small arrays is the sweet spot of StaticArrays putting ordinary arrays to shame in many cases.

Plan for v0.2

  • Consider introduce the PhasePoint type #17 #50
  • Update gradient function to return both value and gradient #56
  • RFC find_good_eps #27
  • More robust and modular way of detecting divergence #16
  • Return more information for each step #59
  • Implement Base.show for all user side types #36
  • RFC Adapter types #28
  • Instantiation of new AbstractMetrics #45
  • Simplifying Metric types by using AbstractPDMat #34
  • Adding noise to step size? #10

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.