-
Notifications
You must be signed in to change notification settings - Fork 18
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
Adaptive proposals #39
base: master
Are you sure you want to change the base?
Conversation
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.
Wow, what a lovely surprise to receive on a Sunday morning! This is great stuff -- really an excellent PR. It came with tests, the code is succinct and easy to review, and the feature is one I've wanted for a long time. Excellently done.
I left a handful of comments, but I think most of them are suggestions you should be able to commit directly by pressing "Commit suggestion". They're primarily style changes, but one docstring could use a little more info.
Thanks for the PR! I'm going to be really happy to have this merged in.
src/adaptive.jl
Outdated
Adaptor(; tune=25, target=0.44, bound=10., δmax=0.2) = | ||
Adaptor(0, 0, tune, target, bound, δmax) | ||
|
||
""" | ||
AdaptiveProposal{P} | ||
|
||
An adaptive Metropolis-Hastings proposal. In order for this to work, the | ||
proposal kernel should implement the `adapted(proposal, δ)` method, where `δ` | ||
is the increment/decrement applied to the scale of the proposal distribution | ||
during adaptation (e.g. for a Normal distribution the scale is `log(σ)`, so | ||
that after adaptation the proposal is `Normal(0, exp(log(σ) + δ))`). |
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.
Can you briefly describe the default Adaptor
in the docstring for AdaptiveProposal
, and notify everyone what the default keywords are for the adaptor?
Co-authored-by: Cameron Pfiffer <[email protected]>
Co-authored-by: Cameron Pfiffer <[email protected]>
Co-authored-by: Cameron Pfiffer <[email protected]>
Co-authored-by: Cameron Pfiffer <[email protected]>
Co-authored-by: Cameron Pfiffer <[email protected]>
Co-authored-by: Cameron Pfiffer <[email protected]>
Co-authored-by: Cameron Pfiffer <[email protected]>
Co-authored-by: Cameron Pfiffer <[email protected]>
Co-authored-by: Cameron Pfiffer <[email protected]>
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.
Thanks for the PR!
I left some additional comments.
src/adaptive.jl
Outdated
mutable struct Adaptor | ||
accepted::Integer | ||
total ::Integer | ||
tune ::Integer # tuning interval |
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.
If possible one should avoid non-concrete fields:
mutable struct Adaptor | |
accepted::Integer | |
total ::Integer | |
tune ::Integer # tuning interval | |
mutable struct Adaptor | |
accepted::Int | |
total::Int | |
tune::Int # tuning interval |
On a more general level, I'm not completely sure if it is useful to have a separate Adaptor
struct, it seems it could just be integrated into AdaptiveProposal
.
On an even more general level, I think it would be better to make this part of the state of the sampler using the AbstractMCMC interface instead of a field of the proposal. With the current design, the proposal will be mutated in every step. However, this (IMO preferred) design requires to implement AbstractMCMC.step
instead of just adding the accept!
call.
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 of course, Int <-> Integer
confusion...
The Adaptor
struct may indeed be superfluous, although I found it a bit clearer separated that way. Also, I considered implementing adaptation for multivariate Normal proposals, which uses a different machinery under the hood, and my initial thought was to implement that as an AdaptiveProposal
but with different Adaptor
type. Of course, that could be implemented as another proposal struct altogether.
I think I understand conceptually your preferred design at the step
level, although ATM my insight in how AbstractMCMC
works is insufficient to see how that should be done, and currently, to me the mutation of the proposals is the most intuitive approach to implement adaptation. The accept!
call seemed like a very simple, but admittedly somewhat hacky, way to enable adaptive proposals.
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 we should punt this problem to a later date. I would like to include accept
/reject
as a field in the Transition
struct, which would make it very easy to count the number of previous acceptances by just adding adding one to the total_acceptances
field in a Transition
. Currently AdvancedMH doesn't track that internally, but I can just modify this code to remove the mutation 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.
It's not only about the number of accepted/rejected steps here though, the state would have to include the updated proposal etc as well, so it won't be solved by including the stats in Transition.
However, I'm fine with postponing this refactoring. Probably best to open an issue so we don't forget it.
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.
In my thinking, you'd add an extra field to Transitions that just accumulates the total number of acceptances, which is easier to get when you have individual acceptances for each draw. I'll open an issue up.
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, I understand (and I think that's a good addition). My point was just that it is not sufficient here.
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've opened an issue (#40).
src/adaptive.jl
Outdated
""" | ||
mutable struct AdaptiveProposal{P} <: Proposal{P} | ||
proposal::P | ||
adaptor ::Adaptor |
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.
As written above, one might want to consider moving the fields from Adaptor
here and maybe even better making it part of a state that is passed to the proposal in every sampling step. Also the updated proposal would be part of a separate state.
Co-authored-by: David Widmann <[email protected]>
Co-authored-by: David Widmann <[email protected]>
Co-authored-by: David Widmann <[email protected]>
The test failures seem to be real, the sampled values do not match the expected ones. As a side remark, probably it would be helpful for debugging to use |
Where do you see this? As far as I can tell, the three failed runs show the following results:
(which is the same as what I have locally). Maybe I'm looking in the wrong place. |
I looked at the raw logs, e.g., https://pipelines.actions.githubusercontent.com/1iyxZmDwGspc6UbQKDLTZ8y3DHazaAGCEXSw02G4avGy4Eell5/_apis/pipelines/1/runs/7302/signedlogcontent/15?urlExpires=2020-11-23T10%3A22%3A22.7581222Z&urlSigningMethod=HMACV1&urlSignature=%2FUDiYzMH2mBCIhIroN0uueS%2FjYsHAv7zGwfFj%2FCie90%3D. The nicely formatted output of the Github Actions is truncated since progress bars are printed (which is why I suggested to use The raw logs are difficult to read but according to the final statement there are two test failures somewhere. And actually, if you scroll up a bit you can find
which I was referring to. Apparently the sample average of the samples of I just checked locally, and all tests pass with the latest release and with master. So it seems this PR breaks something. |
OK, thanks, I saw that too but was confused since I don't think I changed anything related to parallel sampling, and I thought you were referring to the |
Co-authored-by: David Widmann <[email protected]>
end | ||
|
||
@testset "Compare adaptive to simple random walk" begin | ||
data = rand(Normal(2., 1.), 500) |
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.
@arzwa This might be the problem - you redefine data
and hence I assume you implicitly change the density model
which is defined as a closure over data
.
You could just rename the variable here but actually I think the better approach might be to "fix" the data in the model to avoid any such surprises in the future.
I guess this can be achieved by defining
density = let data = data
θ -> insupport(θ) ? sum(logpdf.(dist(θ), data)) : -Inf
end
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.
But I haven't tested it, so make sure it actually fixes the problem 😄
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, I just saw this too, thanks. I'll check and push an updated test suite. (Actually, we could just as well test against the same data defined above in the test suite, but I find testing against a mean different from 0 a bit more reassuring since the sampler actually has to 'move' to somewhere from where it starts).
kwargs = (progress=false, chain_type=StructArray, param_names=["μ", "σ"]) | ||
chain1 = sample(model, spl1, 100000; kwargs...) | ||
chain2 = sample(model, spl2, 100000; kwargs...) |
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.
Can we maybe just define
_sample(args...; kwargs...) = sample(args...; progress = false, kwargs...)
at the top of the test suite and just replace all occurrences of sample
with _sample
? I think the kwargs
definitions are a bit uncommon...
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.
Sure, I often define a named tuple for kwargs that are repeatedly used, but could be an idiosyncratic thing :)
Hi there, a question related to this PR (feel free to move it to the issue section, I'm not sure what the best place to drop this is). I'm currently facing an application where I would really like to use adaptive proposals like those defined in this PR in a Metropolis-within-Gibbs setting (i.e. we have a parameter vector |
Yeah, this should probably be a separate issue -- can you copy it over and I'll drop my comments there? It looks like there's only one thing to change in this PR -- if that is updated I'd be happy to merge this one in. |
OK, I had implemented multivariate normal adaptive proposals and had it working so thought to add it to this PR. Not sure how the test pipeline got messed up? |
# Adaptive proposals are only defined for symmetric proposal distributions | ||
is_symmetric_proposal(::AdaptiveProposal) = true |
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.
If this is the case, it would be good to check this property in an inner constructor.
function q(proposal::AdaptiveProposal, t, t_cond) | ||
return logpdf(proposal, t - t_cond) | ||
end | ||
|
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.
Is this actually needed? It seems like the default for Proposal
should cover this.
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.
Currently there seems to be no default q
for Proposal
. However it's also unnecessary because these adaptive proposals are always symmetric.
F = cholesky(Hermitian(Σ), check=false) | ||
if rank(F.L) == p.d | ||
p.adaptive = MvNormal(PDMat(Σ, F)) | ||
end |
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.
Also here, can't we just use the default constructors of MvNormal
which call PDMat
implicitly?
F = cholesky(Hermitian(Σ), check=false) | |
if rank(F.L) == p.d | |
p.adaptive = MvNormal(PDMat(Σ, F)) | |
end | |
p.adaptive = MvNormal(Σ) |
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 implemented it this way (inspired by the Mamba implementation) to check whether the empirical estimate of the covariance matrix is a proper covariance matrix. If it is we can adapt the proposal distribution without additional computation by feeding the cholesky decomposition to MvNormal this way. How would you do it otherwise, I guess you could use try/catch
but that doesn't seem nicer?
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.
No, I don't think a try
-catch
block would be any better. IMO it is not good to just suppress the errors here and use an incorrect Cholesky decomposition with possibly negative eigenvalues. I would suggest the following:
- If possible, update the Cholesky decomposition (or some other parametrization of the covariance matrix) iteratively. Usually this is more efficient than recomputing the factorization in every step and it avoid the numerical problems.
- Often calling
Matrix(Symmetric(Sigma))
is sufficient to avoid problems with matrices that are not completely symmetric and for which therefore the Cholesky decomposition fails. - Alternatively, use
PositiveFactorizations
.
IMO the first alternative would clearly be the best, if possible.
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 just had a quick look at Haario et al. and the update formula of the covariance matrix in eq (3). It seems that indeed the update could be performed by only d + 3
rank 1 up- and downdates which each can be performed in O(d^2). Actually, if eps = 0
, then only 3 rank 1 up- and downdates are needed and therefore the iterative update of the Cholesky decomposition would be much cheaper than recomputing the decomposition in O(d^3) operations. The rank 1 up- and downdates are implemented in LinearAlgebra.lowrankupdate!
and LinearAlgebra.lowrankdowndate!
(and their corresponding out-of-place methods).
I think this would be the preferable method for updating the Cholesky decomposition. Probably it would also be cheaper to save just the Cholesky decomposition and not wrap it in a MvNormal
object since it is trivial to sample from the multivariate normal distribution with the Cholesky decomposition.
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.
That sounds interesting and worthwhile, have to look at it. FWIW I just based my code on the description in the Roberts & Rosenthal paper and the Mamba implementation, since I simply wanted to use this for a problem I'm having.
I had the impression from the code that there is a preference to use Distributions.jl distributions for sampling, that's why I wrapped them in MvNormal objects instead of using the Cholesky factor directly (when both the full matrix and cholesky factors are available, it is as cheap to put them in an MvNormal). When updating the cholesky factor directly I agree it would be better to to do as you suggest.
function propose(rng::Random.AbstractRNG, proposal::AdaptiveMvNormal, m::DensityModel) | ||
return rand(rng, proposal) | ||
end | ||
|
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.
Is this not covered by the default for Proposal
?
@@ -18,7 +18,7 @@ | |||
Random.seed!(100) | |||
sampler = Ensemble(1_000, StretchProposal([InverseGamma(2, 3), Normal(0, 1)])) | |||
chain = sample(model, sampler, 1_000; | |||
param_names = ["s", "m"], chain_type = Chains) | |||
param_names = ["s", "m"], chain_type = Chains, progress = false) |
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.
Co-authored-by: David Widmann <[email protected]>
Co-authored-by: David Widmann <[email protected]>
Co-authored-by: David Widmann <[email protected]>
Co-authored-by: David Widmann <[email protected]>
Co-authored-by: David Widmann <[email protected]>
Co-authored-by: David Widmann <[email protected]>
Anything missing from this PR? If there is nothing major standing in the way, maybe we should revisit and get it merged asap. |
Hi, I should have a look at it again, @devmotion had some good suggestions on the multivariate adaptive normal kernel, which I did not yet look into further at as I got busy with other stuff. The univariate adaptive proposals should be fine I think. |
Is this still of interest/relevant? I'd definitely be interested in using this and may be able to help finish it up. |
It's still relevant; please feel free to take this over. |
Hi, I implemented some very basic adaptive Metropolis-Hastings proposals that may be of interest for the
AdvancedMH.jl
package. These are basically simple symmetric random-walk proposals where the scale is subjected to diminishing adaptation (see e.g. section 3 here). These are mainly of interest in Metropolis-within-Gibbs-like algorithms, and they could be of interest in Turing. For instance, for a simple test case:Also, this is my first PR to a collaborative project, and am taking this as an opportunity to learn how to contribute to projects using git (hopefully with something useful). In other words, I'm not sure if I'm doing this right :)
If I find some time, and this is considered useful, I'd like to port some other related stuff I've used in other projects to AdvancedMH as well.