-
Notifications
You must be signed in to change notification settings - Fork 219
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
Allow usage of AbstractSampler
#2008
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
5136d05
initial work on allowing AdvancedHMC samplers
torfjelde 6f4f328
simplify the hacky initialize_nuts method
torfjelde 0c711ed
slight generalization
torfjelde 1a13d50
remove unnecessary type constraint
torfjelde ed2077b
rever changes to sample overloads
torfjelde 8a489f6
use a subtype of InferenceAlgorithm to wrap any sampler
torfjelde 59ac28b
improve usage of SamplerWrapper
torfjelde 008a853
renamed hmc_new.jl to something a bit more indicative
torfjelde 8f698dc
added support for AdvancedMH
torfjelde 817867c
Merge branch 'master' into torfjelde/allow-abstractsampler-draft
torfjelde 2b73181
forgot to change include
torfjelde 5ef1fa8
renamed SamplerWrapper to ExternalSampler and provided a function ext…
torfjelde 82ab311
added tests for Advanced{HMC,MH}
torfjelde 761ff45
Merge branch 'master' into torfjelde/allow-abstractsampler-draft
torfjelde a1fabca
Merge branch 'master' into torfjelde/allow-abstractsampler-draft
torfjelde 335e868
fixed external tests
torfjelde d1afddd
change target acceptance rate
torfjelde 6064834
fixed optim tests
torfjelde 63e37f5
remove NelderMead from tests
torfjelde 22cdfeb
allow models with one variance parameter per observation to fail MLE …
torfjelde b08dd82
no tests (#2028)
JaimeRZP b0503e5
Merge branch 'master' into torfjelde/allow-abstractsampler-draft
yebai 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 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 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 |
---|---|---|
@@ -0,0 +1,87 @@ | ||
struct TuringState{S,F} | ||
state::S | ||
logdensity::F | ||
end | ||
|
||
struct TuringTransition{T,NT<:NamedTuple,F<:AbstractFloat} | ||
θ::T | ||
lp::F | ||
stat::NT | ||
end | ||
|
||
function TuringTransition(vi::AbstractVarInfo, t) | ||
theta = tonamedtuple(vi) | ||
lp = getlogp(vi) | ||
return TuringTransition(theta, lp, getstats(t)) | ||
end | ||
|
||
metadata(t::TuringTransition) = merge((lp = t.lp,), t.stat) | ||
DynamicPPL.getlogp(t::TuringTransition) = t.lp | ||
|
||
state_to_turing(f::DynamicPPL.LogDensityFunction, state) = TuringState(state, f) | ||
function transition_to_turing(f::DynamicPPL.LogDensityFunction, transition) | ||
θ = getparams(transition) | ||
varinfo = DynamicPPL.unflatten(f.varinfo, θ) | ||
# TODO: `deepcopy` is overkill; make more efficient. | ||
varinfo = DynamicPPL.invlink!!(deepcopy(varinfo), f.model) | ||
return TuringTransition(varinfo, transition) | ||
end | ||
|
||
# NOTE: Only thing that depends on the underlying sampler. | ||
# Something similar should be part of AbstractMCMC at some point: | ||
# https://github.com/TuringLang/AbstractMCMC.jl/pull/86 | ||
getparams(transition::AdvancedHMC.Transition) = transition.z.θ | ||
getstats(transition::AdvancedHMC.Transition) = transition.stat | ||
|
||
getparams(transition::AdvancedMH.Transition) = transition.params | ||
getstats(transition) = NamedTuple() | ||
|
||
getvarinfo(f::DynamicPPL.LogDensityFunction) = f.varinfo | ||
getvarinfo(f::LogDensityProblemsAD.ADGradientWrapper) = getvarinfo(parent(f)) | ||
|
||
setvarinfo(f::DynamicPPL.LogDensityFunction, varinfo) = Setfield.@set f.varinfo = varinfo | ||
setvarinfo(f::LogDensityProblemsAD.ADGradientWrapper, varinfo) = setvarinfo(parent(f), varinfo) | ||
|
||
# TODO: Do we also support `resume`, etc? | ||
function AbstractMCMC.step( | ||
rng::Random.AbstractRNG, | ||
model::DynamicPPL.Model, | ||
sampler_wrapper::Sampler{<:ExternalSampler}; | ||
kwargs... | ||
) | ||
sampler = sampler_wrapper.alg.sampler | ||
|
||
# Create a log-density function with an implementation of the | ||
# gradient so we ensure that we're using the same AD backend as in Turing. | ||
f = LogDensityProblemsAD.ADgradient(DynamicPPL.LogDensityFunction(model)) | ||
|
||
# Link the varinfo. | ||
f = setvarinfo(f, DynamicPPL.link!!(getvarinfo(f), model)) | ||
|
||
# Then just call `AdvancedHMC.step` with the right arguments. | ||
transition_inner, state_inner = AbstractMCMC.step( | ||
rng, AbstractMCMC.LogDensityModel(f), sampler; kwargs... | ||
) | ||
|
||
# Update the `state` | ||
return transition_to_turing(f, transition_inner), state_to_turing(f, state_inner) | ||
end | ||
|
||
function AbstractMCMC.step( | ||
rng::Random.AbstractRNG, | ||
model::DynamicPPL.Model, | ||
sampler_wrapper::Sampler{<:ExternalSampler}, | ||
state::TuringState; | ||
kwargs... | ||
) | ||
sampler = sampler_wrapper.alg.sampler | ||
f = state.logdensity | ||
|
||
# Then just call `AdvancedHMC.step` with the right arguments. | ||
transition_inner, state_inner = AbstractMCMC.step( | ||
rng, AbstractMCMC.LogDensityModel(f), sampler, state.state; kwargs... | ||
) | ||
|
||
# Update the `state` | ||
return transition_to_turing(f, transition_inner), state_to_turing(f, state_inner) | ||
end |
This file contains 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 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 |
---|---|---|
@@ -0,0 +1,75 @@ | ||
using Turing.Inference: AdvancedHMC | ||
|
||
function initialize_nuts(model::Turing.Model) | ||
# Create a log-density function with an implementation of the | ||
# gradient so we ensure that we're using the same AD backend as in Turing. | ||
f = LogDensityProblemsAD.ADgradient(DynamicPPL.LogDensityFunction(model)) | ||
|
||
# Link the varinfo. | ||
f = Turing.Inference.setvarinfo(f, DynamicPPL.link!!(Turing.Inference.getvarinfo(f), model)) | ||
|
||
# Choose parameter dimensionality and initial parameter value | ||
D = LogDensityProblems.dimension(f) | ||
initial_θ = rand(D) .- 0.5 | ||
|
||
# Define a Hamiltonian system | ||
metric = AdvancedHMC.DiagEuclideanMetric(D) | ||
hamiltonian = AdvancedHMC.Hamiltonian(metric, f) | ||
|
||
# Define a leapfrog solver, with initial step size chosen heuristically | ||
initial_ϵ = AdvancedHMC.find_good_stepsize(hamiltonian, initial_θ) | ||
integrator = AdvancedHMC.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 | ||
proposal = AdvancedHMC.NUTS{AdvancedHMC.MultinomialTS,AdvancedHMC.GeneralisedNoUTurn}(integrator) | ||
adaptor = AdvancedHMC.StanHMCAdaptor( | ||
AdvancedHMC.MassMatrixAdaptor(metric), | ||
AdvancedHMC.StepSizeAdaptor(0.65, integrator) | ||
) | ||
|
||
return AdvancedHMC.HMCSampler(proposal, metric, adaptor) | ||
end | ||
|
||
|
||
function initialize_mh(model) | ||
f = DynamicPPL.LogDensityFunction(model) | ||
d = LogDensityProblems.dimension(f) | ||
return AdvancedMH.RWMH(MvNormal(Zeros(d), 0.1 * I)) | ||
end | ||
|
||
@testset "External samplers" begin | ||
@testset "AdvancedHMC.jl" begin | ||
for model in DynamicPPL.TestUtils.DEMO_MODELS | ||
# Need some functionality to initialize the sampler. | ||
# TODO: Remove this once the constructors in the respective packages become "lazy". | ||
sampler = initialize_nuts(model); | ||
DynamicPPL.TestUtils.test_sampler( | ||
[model], | ||
DynamicPPL.Sampler(externalsampler(sampler), model), | ||
5_000; | ||
nadapts=1_000, | ||
discard_initial=1_000, | ||
rtol=0.2 | ||
) | ||
end | ||
end | ||
|
||
@testset "AdvancedMH.jl" begin | ||
for model in DynamicPPL.TestUtils.DEMO_MODELS | ||
# Need some functionality to initialize the sampler. | ||
# TODO: Remove this once the constructors in the respective packages become "lazy". | ||
sampler = initialize_mh(model); | ||
DynamicPPL.TestUtils.test_sampler( | ||
[model], | ||
DynamicPPL.Sampler(externalsampler(sampler), model), | ||
10_000; | ||
discard_initial=1_000, | ||
thinning=10, | ||
rtol=0.2 | ||
) | ||
end | ||
end | ||
end |
This file contains 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 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.
@torfjelde Isn't this obsolete now that #2026 was merged?
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.
I think so. @JaimeRZP, can you do a follow-up PR to unify these
Transition
types?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.
Yes it is, which I was aware of; me and Jaime wanted to wait until that had been merged before merging this PR.
I was planning to incorporate those changes into this PR before merging. We're also missing a version-bump.
I'd appreciate it if we left merging of a PR to the person who opened it, unless otherwise explicitly stated. In particular now when it's just a matter of days before I'll be back in full development capacity again. This has happened quite few times now :/
Also, it's not like this PR needs to be merged to be able to develop other functionality; it's easy enough to just depend on the branch directly.
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.
I was under the impression that @JaimeRZP needs this to be released. Sorry for the rush -- hopefully, it didn't break anything! We can always add more changes in a follow-up PR.
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.
Ah gotcha. @JaimeRZP you can always just do
]add Turing#torfjelde/allow-abstractsampler-draft
if you want to try out recent developments. And if you want to develop features based on this branch, just create a branch based on this PR and then continue from there, as you did with #2028 :)