-
Notifications
You must be signed in to change notification settings - Fork 37
[Merged by Bors] - Method to extract loglikelihoods #166
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
14 commits
Select commit
Hold shift + click to select a range
de8f869
added a loglikelihoods method to extract, well, loglikelihoods
torfjelde 094792e
added testing and fixed a bug making it use the prior instead
torfjelde 4f2b146
added docstring
torfjelde 7e5a8f0
implemented get_likelihoods using Context instead, thanks @devmotion
torfjelde 1c43c9f
fixed docstring
torfjelde 63d27eb
Update src/loglikelihoods.jl
torfjelde 334cb98
fixed typo
torfjelde db4a850
implemented suggested changes @devmotion
torfjelde ee55385
added push! for ElementwiseContext and defaults to varnames
torfjelde 4605c22
suggested changes
torfjelde 5f5d954
improved elementwise_loglikelihood for model and varinfo
torfjelde 09bd74f
version bump
torfjelde 57c03fe
added tests to runtests.jl
torfjelde 5cd7b0b
fixed import of Turing in tests and added export of elementwise_logli…
torfjelde 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| # Context version | ||
| struct ElementwiseLikelihoodContext{A, Ctx} <: AbstractContext | ||
| loglikelihoods::A | ||
| ctx::Ctx | ||
| end | ||
|
|
||
| function ElementwiseLikelihoodContext( | ||
| likelihoods = Dict{VarName, Vector{Float64}}(), | ||
| ctx::AbstractContext = LikelihoodContext() | ||
| ) | ||
| return ElementwiseLikelihoodContext{typeof(likelihoods),typeof(ctx)}(likelihoods, ctx) | ||
| end | ||
|
|
||
| function Base.push!( | ||
| ctx::ElementwiseLikelihoodContext{Dict{VarName, Vector{Float64}}}, | ||
| vn::VarName, | ||
| logp::Real | ||
| ) | ||
| lookup = ctx.loglikelihoods | ||
| ℓ = get!(lookup, vn, Float64[]) | ||
| push!(ℓ, logp) | ||
| end | ||
|
|
||
| function Base.push!( | ||
| ctx::ElementwiseLikelihoodContext{Dict{VarName, Float64}}, | ||
| vn::VarName, | ||
| logp::Real | ||
| ) | ||
| ctx.loglikelihoods[vn] = logp | ||
| end | ||
|
|
||
|
|
||
| function tilde_assume(rng, ctx::ElementwiseLikelihoodContext, sampler, right, vn, inds, vi) | ||
| return tilde_assume(rng, ctx.ctx, sampler, right, vn, inds, vi) | ||
| end | ||
|
|
||
| function dot_tilde_assume(rng, ctx::ElementwiseLikelihoodContext, sampler, right, left, vn, inds, vi) | ||
| value, logp = dot_tilde(rng, ctx.ctx, sampler, right, left, vn, inds, vi) | ||
| acclogp!(vi, logp) | ||
| return value | ||
| end | ||
|
|
||
|
|
||
| function tilde_observe(ctx::ElementwiseLikelihoodContext, sampler, right, left, vname, vinds, vi) | ||
| # This is slightly unfortunate since it is not completely generic... | ||
| # Ideally we would call `tilde_observe` recursively but then we don't get the | ||
| # loglikelihood value. | ||
| logp = tilde(ctx.ctx, sampler, right, left, vi) | ||
| acclogp!(vi, logp) | ||
|
|
||
| # track loglikelihood value | ||
| push!(ctx, vname, logp) | ||
|
|
||
| return left | ||
| end | ||
|
|
||
|
|
||
| """ | ||
| elementwise_loglikelihoods(model::Model, chain::Chains) | ||
|
|
||
| Runs `model` on each sample in `chain` returning an array of arrays with | ||
| the i-th element inner arrays corresponding to the the likelihood of the i-th | ||
| observation for that particular sample in `chain`. | ||
|
|
||
| # Notes | ||
| Say `y` is a `Vector` of `n` i.i.d. `Normal(μ, σ)` variables, with `μ` and `σ` | ||
| both being `<:Real`. Then the *observe* (i.e. when the left-hand side is an | ||
| *observation*) statements can be implemented in two ways: | ||
| ```julia | ||
| for i in eachindex(y) | ||
| y[i] ~ Normal(μ, σ) | ||
| end | ||
| ``` | ||
| or | ||
| ```julia | ||
| y ~ MvNormal(fill(μ, n), fill(σ, n)) | ||
| ``` | ||
| Unfortunately, just by looking at the latter statement, it's impossible to tell whether or | ||
| not this is one *single* observation which is `n` dimensional OR if we have *multiple* | ||
| 1-dimensional observations. Therefore, `loglikelihoods` will only work with the first | ||
| example. | ||
|
|
||
| # Examples | ||
| ```julia-repl | ||
| julia> using DynamicPPL, Turing | ||
|
|
||
| julia> @model function demo(xs, y) | ||
| s ~ InverseGamma(2, 3) | ||
| m ~ Normal(0, √s) | ||
| for i in eachindex(xs) | ||
| xs[i] ~ Normal(m, √s) | ||
| end | ||
|
|
||
| y ~ Normal(m, √s) | ||
| end | ||
| demo (generic function with 1 method) | ||
|
|
||
| julia> model = demo(randn(3), randn()); | ||
|
|
||
| julia> chain = sample(model, MH(), 10); | ||
|
|
||
| julia> DynamicPPL.elementwise_loglikelihoods(model, chain) | ||
| Dict{String,Array{Float64,1}} with 4 entries: | ||
| "xs[3]" => [-1.02616, -1.26931, -1.05003, -5.05458, -1.33825, -1.02904, -1.23761, -1.30128, -1.04872, -2.03716] | ||
| "xs[1]" => [-2.08205, -2.51387, -3.03175, -2.5981, -2.31322, -2.62284, -2.70874, -1.18617, -1.36281, -4.39839] | ||
| "xs[2]" => [-2.20604, -2.63495, -3.22802, -2.48785, -2.40941, -2.78791, -2.85013, -1.24081, -1.46019, -4.59025] | ||
| "y" => [-1.36627, -1.21964, -1.03342, -7.46617, -1.3234, -1.14536, -1.14781, -2.48912, -2.23705, -1.26267] | ||
| ``` | ||
| """ | ||
| function elementwise_loglikelihoods(model::Model, chain) | ||
| # Get the data by executing the model once | ||
| ctx = ElementwiseLikelihoodContext() | ||
| spl = SampleFromPrior() | ||
| vi = VarInfo(model) | ||
|
|
||
| iters = Iterators.product(1:size(chain, 1), 1:size(chain, 3)) | ||
| for (sample_idx, chain_idx) in iters | ||
| # Update the values | ||
| setval!(vi, chain, sample_idx, chain_idx) | ||
|
|
||
| # Execute model | ||
| model(vi, spl, ctx) | ||
| end | ||
| return ctx.loglikelihoods | ||
| end | ||
|
|
||
| function elementwise_loglikelihoods(model::Model, varinfo::AbstractVarInfo) | ||
| ctx = ElementwiseLikelihoodContext(Dict{VarName, Float64}()) | ||
| model(varinfo, SampleFromPrior(), ctx) | ||
| return ctx.loglikelihoods | ||
devmotion marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| using .Turing | ||
|
|
||
| @testset "loglikelihoods" begin | ||
| @model function demo(xs, y) | ||
| s ~ InverseGamma(2, 3) | ||
| m ~ Normal(0, √s) | ||
| for i in eachindex(xs) | ||
| xs[i] ~ Normal(m, √s) | ||
| end | ||
|
|
||
| y ~ Normal(m, √s) | ||
| end | ||
|
|
||
| xs = randn(3); | ||
| y = randn(); | ||
| model = demo(xs, y); | ||
| chain = sample(model, MH(), 100); | ||
| results = elementwise_loglikelihoods(model, chain) | ||
| var_to_likelihoods = Dict(string(varname) => logliks for (varname, logliks) in results) | ||
| @test haskey(var_to_likelihoods, "xs[1]") | ||
| @test haskey(var_to_likelihoods, "xs[2]") | ||
| @test haskey(var_to_likelihoods, "xs[3]") | ||
| @test haskey(var_to_likelihoods, "y") | ||
|
|
||
| for (i, (s, m)) in enumerate(zip(chain[:s], chain[:m])) | ||
| @test logpdf(Normal(m, √s), xs[1]) == var_to_likelihoods["xs[1]"][i] | ||
| @test logpdf(Normal(m, √s), xs[2]) == var_to_likelihoods["xs[2]"][i] | ||
| @test logpdf(Normal(m, √s), xs[3]) == var_to_likelihoods["xs[3]"][i] | ||
| @test logpdf(Normal(m, √s), y) == var_to_likelihoods["y"][i] | ||
| end | ||
|
|
||
| var_info = VarInfo(model) | ||
| results = DynamicPPL.elementwise_loglikelihoods(model, var_info) | ||
| var_to_likelihoods = Dict(string(vn) => ℓ for (vn, ℓ) in results) | ||
| s, m = var_info[SampleFromPrior()] | ||
| @test logpdf(Normal(m, √s), xs[1]) == var_to_likelihoods["xs[1]"] | ||
| @test logpdf(Normal(m, √s), xs[2]) == var_to_likelihoods["xs[2]"] | ||
| @test logpdf(Normal(m, √s), xs[3]) == var_to_likelihoods["xs[3]"] | ||
| @test logpdf(Normal(m, √s), y) == var_to_likelihoods["y"] | ||
| 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
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.
So here
empty!is not needed?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.
Actually,
empty!will ruin it! I did that initially, butempty!also made it so that values would be resampled. So it ended up sampling from the prior instead.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.
Hmm but why would it resample values in this case? Shouldn't
setval!fix them? There's something going on with thisempty!/setval!thing that I don't understand 🤔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, okay then there's something weird. I thought I just had misunderstood something, but if you also don't know why that's the case then there's something going on 😅
Can it be the fact that
empty!clears the"del"flag +setval!does NOT set it tofalse? So then we you run the model again, it will resample?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.
Yeah, something is wrong:
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.
Figured it out:
empty!clearsvi.metadata.$n.vnsfor every$ninnames, so the following never touches_setval_kernel!:DynamicPPL.jl/src/varinfo.jl
Lines 1167 to 1171 in 334cb98