-
Notifications
You must be signed in to change notification settings - Fork 230
Actually perform iteration with DynamicHMC #1186
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,148 +1,172 @@ | ||
| ### | ||
| ### DynamicHMC backend - https://github.com/tpapp/DynamicHMC.jl | ||
| ### | ||
|
|
||
| """ | ||
| DynamicNUTS | ||
|
|
||
| Dynamic No U-Turn Sampling algorithm provided by the DynamicHMC package. To use it, make | ||
| sure you have the LogDensityProblems package and DynamicHMC package (version >= 2) loaded: | ||
|
|
||
| ```julia | ||
| using LogDensityProblems, DynamicHMC | ||
| ``` | ||
| """ | ||
| struct DynamicNUTS{AD, space} <: Hamiltonian{AD} end | ||
|
|
||
| using LogDensityProblems: LogDensityProblems | ||
| DynamicNUTS(args...) = DynamicNUTS{ADBackend()}(args...) | ||
| DynamicNUTS{AD}(space::Symbol...) where AD = DynamicNUTS{AD, space}() | ||
|
|
||
| getspace(::DynamicNUTS{<:Any, space}) where {space} = space | ||
|
|
||
| struct FunctionLogDensity{F} | ||
| dimension::Int | ||
| f::F | ||
| mutable struct DynamicNUTSState{V<:VarInfo} <: AbstractSamplerState | ||
| vi::V | ||
| end | ||
|
|
||
| LogDensityProblems.dimension(ℓ::FunctionLogDensity) = ℓ.dimension | ||
| function Sampler( | ||
| alg::DynamicNUTS, | ||
| model::Model, | ||
| s::Selector=Selector() | ||
| ) | ||
| # Construct a state, using a default function. | ||
| state = DynamicNUTSState(VarInfo(model)) | ||
|
|
||
| function LogDensityProblems.capabilities(::Type{<:FunctionLogDensity}) | ||
| LogDensityProblems.LogDensityOrder{1}() | ||
| # Return a new sampler. | ||
| return Sampler(alg, Dict{Symbol,Any}(), s, state) | ||
| end | ||
|
|
||
| function LogDensityProblems.logdensity(ℓ::FunctionLogDensity, x::AbstractVector) | ||
| first(ℓ.f(x)) | ||
| """ | ||
| DynamicNUTSTransition | ||
|
|
||
| Transition for the `DynamicNUTS` sampler. | ||
| """ | ||
| struct DynamicNUTSTransition{T,F<:AbstractFloat,QType,H,S} | ||
| θ::T | ||
| lp::F | ||
| Q::QType | ||
| hamiltonian::H | ||
| stepsize::S | ||
| end | ||
|
|
||
| function LogDensityProblems.logdensity_and_gradient(ℓ::FunctionLogDensity, | ||
| x::AbstractVector) | ||
| ℓ.f(x) | ||
| function additional_parameters(::Type{<:DynamicNUTSTransition}) | ||
| return [:lp] | ||
| end | ||
|
|
||
| """ | ||
| DynamicNUTS() | ||
| # Wrapper for the log density function | ||
| struct LogDensity{M<:Model,S<:Sampler} | ||
| model::M | ||
| spl::S | ||
| end | ||
|
|
||
| Dynamic No U-Turn Sampling algorithm provided by the DynamicHMC package. To use it, make | ||
| sure you have the DynamicHMC package (version `2.*`) loaded: | ||
| function LogDensityProblems.dimension(ℓ::LogDensity) | ||
| spl = ℓ.spl | ||
| return length(spl.state.vi[spl]) | ||
| end | ||
|
|
||
| ```julia | ||
| using DynamicHMC | ||
| `` | ||
| """ | ||
| DynamicNUTS(args...) = DynamicNUTS{ADBackend()}(args...) | ||
| DynamicNUTS{AD}() where AD = DynamicNUTS{AD, ()}() | ||
| function DynamicNUTS{AD}(space::Symbol...) where AD | ||
| DynamicNUTS{AD, space}() | ||
| function LogDensityProblems.capabilities(::Type{<:LogDensity}) | ||
| LogDensityProblems.LogDensityOrder{1}() | ||
| end | ||
|
|
||
| mutable struct DynamicNUTSState{V<:VarInfo, D} <: AbstractSamplerState | ||
| vi::V | ||
| draws::Vector{D} | ||
| function LogDensityProblems.logdensity(ℓ::LogDensity, x::AbstractVector) | ||
| sampler = ℓ.sampler | ||
| vi = sampler.state.vi | ||
|
|
||
| x_old = vi[sampler] | ||
| lj_old = getlogp(vi) | ||
|
|
||
| vi[sampler] = x | ||
| runmodel!(ℓ.model, vi, sampler) | ||
| lj = getlogp(vi) | ||
|
|
||
| vi[sampler] = x_old | ||
| setlogp!(vi, lj_old) | ||
|
|
||
| return lj | ||
| end | ||
|
|
||
| getspace(::DynamicNUTS{<:Any, space}) where {space} = space | ||
| function LogDensityProblems.logdensity_and_gradient(ℓ::LogDensity, | ||
| x::AbstractVector) | ||
| spl = ℓ.spl | ||
| return gradient_logp(x, spl.state.vi, ℓ.model, spl) | ||
| end | ||
|
|
||
| function AbstractMCMC.sample_init!( | ||
| function AbstractMCMC.step!( | ||
| rng::AbstractRNG, | ||
| model::Model, | ||
| spl::Sampler{<:DynamicNUTS}, | ||
| N::Integer; | ||
| ::Integer, | ||
| ::Nothing; | ||
| kwargs... | ||
| ) | ||
| # Set up lp function. | ||
| function _lp(x) | ||
| gradient_logp(x, spl.state.vi, model, spl) | ||
| # Convert to transformed space. | ||
| vi = spl.state.vi | ||
| if !islinked(vi, spl) | ||
| Turing.DEBUG && @debug "X-> R..." | ||
| link!(vi, spl) | ||
| runmodel!(model, vi, spl) | ||
| end | ||
|
|
||
| runmodel!(model, spl.state.vi, SampleFromUniform()) | ||
|
|
||
| if spl.selector.tag == :default | ||
| link!(spl.state.vi, spl) | ||
| runmodel!(model, spl.state.vi, spl) | ||
| end | ||
|
|
||
| # Set the parameters to a starting value. | ||
| initialize_parameters!(spl; kwargs...) | ||
|
|
||
| results = mcmc_with_warmup( | ||
| # Initial step | ||
| results = DynamicHMC.mcmc_keep_warmup( | ||
| rng, | ||
| FunctionLogDensity( | ||
| length(spl.state.vi[spl]), | ||
| _lp | ||
| ), | ||
| N | ||
| LogDensity(model, spl), | ||
| 0; | ||
| reporter = DynamicHMC.NoProgressReport() | ||
| ) | ||
| steps = DynamicHMC.mcmc_steps(results.sampling_logdensity, results.final_warmup_state) | ||
| Q, stats = DynamicHMC.mcmc_next_step(steps, results.final_warmup_state.Q) | ||
|
|
||
| # Update the sample. | ||
| vi[spl] = Q.q | ||
| logp = stats.π | ||
| setlogp!(vi, logp) | ||
|
|
||
| spl.state.draws = results.chain | ||
| return DynamicNUTSTransition(tonamedtuple(vi), logp, Q, steps.H, steps.ϵ) | ||
| end | ||
|
|
||
| function AbstractMCMC.step!( | ||
| rng::AbstractRNG, | ||
| model::Model, | ||
| spl::Sampler{<:DynamicNUTS}, | ||
| N::Integer, | ||
| transition; | ||
| ::Integer, | ||
| transition::DynamicNUTSTransition; | ||
| kwargs... | ||
| ) | ||
| # Pop the next draw off the vector. | ||
| draw = popfirst!(spl.state.draws) | ||
| spl.state.vi[spl] = draw | ||
| return Transition(spl) | ||
| end | ||
|
|
||
| function Sampler( | ||
| alg::DynamicNUTS, | ||
| model::Model, | ||
| s::Selector=Selector() | ||
| ) | ||
| # Construct a state, using a default function. | ||
| state = DynamicNUTSState(VarInfo(model), []) | ||
|
|
||
| # Return a new sampler. | ||
| return Sampler(alg, Dict{Symbol,Any}(), s, state) | ||
| # Compute next sample. | ||
| hamiltonian = transition.hamiltonian | ||
| stepsize = transition.stepsize | ||
| steps = DynamicHMC.MCMCSteps(rng, DynamicHMC.NUTS(), hamiltonian, stepsize) | ||
| Q, stats = DynamicHMC.mcmc_next_step(steps, transition.Q) | ||
|
|
||
| # Update the sample. | ||
| vi = spl.state.vi | ||
| vi[spl] = Q.q | ||
| logp = stats.π | ||
| setlogp!(vi, logp) | ||
|
|
||
| return DynamicNUTSTransition(tonamedtuple(vi), logp, Q, hamiltonian, stepsize) | ||
| end | ||
|
|
||
| # Disable the progress logging for DynamicHMC, since it has its own progress meter. | ||
| function AbstractMCMC.sample( | ||
| rng::AbstractRNG, | ||
| model::AbstractModel, | ||
| alg::DynamicNUTS, | ||
| # Do not store fields specific to DynamicHMC. | ||
| function AbstractMCMC.transitions_init( | ||
| transition::DynamicNUTSTransition, | ||
| ::Model, | ||
| ::Sampler{<:DynamicNUTS}, | ||
| N::Integer; | ||
| chain_type=MCMCChains.Chains, | ||
| resume_from=nothing, | ||
| progress=PROGRESS[], | ||
| kwargs... | ||
| ) | ||
| if progress | ||
| @warn "[$(alg_str(alg))] Progress logging in Turing is disabled since DynamicHMC provides its own progress meter" | ||
| end | ||
| if resume_from === nothing | ||
| return AbstractMCMC.sample(rng, model, Sampler(alg, model), N; | ||
| chain_type=chain_type, progress=false, kwargs...) | ||
| else | ||
| return resume(resume_from, N; chain_type=chain_type, progress=false, kwargs...) | ||
| end | ||
| return Vector{Transition{typeof(transition.θ),typeof(transition.lp)}}(undef, N) | ||
| end | ||
|
|
||
| function AbstractMCMC.psample( | ||
| rng::AbstractRNG, | ||
| model::AbstractModel, | ||
| alg::DynamicNUTS, | ||
| N::Integer, | ||
| n_chains::Integer; | ||
| chain_type=MCMCChains.Chains, | ||
| progress=PROGRESS[], | ||
| function AbstractMCMC.transitions_save!( | ||
| transitions::Vector{<:Transition}, | ||
| iteration::Integer, | ||
| transition::DynamicNUTSTransition, | ||
| ::Model, | ||
| ::Sampler{<:DynamicNUTS}, | ||
| ::Integer; | ||
| kwargs... | ||
| ) | ||
| if progress | ||
| @warn "[$(alg_str(alg))] Progress logging in Turing is disabled since DynamicHMC provides its own progress meter" | ||
| end | ||
| return AbstractMCMC.psample(rng, model, Sampler(alg, model), N, n_chains; | ||
| chain_type=chain_type, progress=false, kwargs...) | ||
| transitions[iteration] = Transition(transition.θ, transition.lp) | ||
| return | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pkg.installedis deprecated on Julia 1.4. I assume that it is unlikely that anyone will run the tests with DynamicHMC < 2 and according to the comment the bug (?) was observed on 32bit with DynamicHMC < 2, so I guess it should be safe to remove the check completely.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Happy to remove this check.