Skip to content

Provide AD gradient for MLE/MAP #1369

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

Merged
merged 9 commits into from
Aug 20, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "Turing"
uuid = "fce5fe82-541a-59a6-adf8-730c64b5f9a0"
version = "0.13.0"
version = "0.13.1"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should make sure that we haven't introduced any breaking changes since 0.13.0. (IMO we should adopt the ColPrac practice of making patch releases for every PR).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll just bump it up to 0.14.0. Honestly at this point we should consider moving to 1.0 as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More importantly, current 0.13.0 is by default failing so ] add Turing and using Turing will fail. I think maybe you guys want to bump up the version really soon...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We first have to fix the bug introduced by the changes in PDMats 0.10 on master before releasing 0.14.0. What was your package setup that failed, i.e. can you post the output of ] st?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I have mine on Turing#master, but there are more than one guys on slack that faces an issue: ] add Turing installs an older version and using Turing somehow fails.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually these problems are caused by unbounded compatibilities of old Turing versions (there are many closed issues in the repo here). These issues should be fixed by running ] add [email protected] and possibly adjusting conflicting packages (by users) and adding correct bounds in the registry (by us). I fixed some bounds a while ago, but it seems the old version are still missing some compatibilty bounds.


[deps]
AbstractMCMC = "80f14c24-f653-4e6a-9b94-39d6b0f70001"
Expand Down
12 changes: 8 additions & 4 deletions src/core/ad.jl
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ ADBackend(::Val) = error("The requested AD backend is not available. Make sure t
Find the autodifferentiation backend of the algorithm `alg`.
"""
getADbackend(spl::Sampler) = getADbackend(spl.alg)
getADbackend(spl::SampleFromPrior) = ADBackend()()

"""
gradient_logp(
Expand All @@ -77,9 +78,10 @@ function gradient_logp(
θ::AbstractVector{<:Real},
vi::VarInfo,
model::Model,
sampler::Sampler
sampler::AbstractSampler,
ctx::DynamicPPL.AbstractContext = DynamicPPL.DefaultContext()
)
return gradient_logp(getADbackend(sampler), θ, vi, model, sampler)
return gradient_logp(getADbackend(sampler), θ, vi, model, sampler, ctx)
end

"""
Expand All @@ -100,12 +102,13 @@ function gradient_logp(
vi::VarInfo,
model::Model,
sampler::AbstractSampler=SampleFromPrior(),
ctx::DynamicPPL.AbstractContext = DynamicPPL.DefaultContext()
)
# Define function to compute log joint.
logp_old = getlogp(vi)
function f(θ)
new_vi = VarInfo(vi, sampler, θ)
model(new_vi, sampler)
model(new_vi, sampler, ctx)
logp = getlogp(new_vi)
setlogp!(vi, ForwardDiff.value(logp))
return logp
Expand All @@ -127,13 +130,14 @@ function gradient_logp(
vi::VarInfo,
model::Model,
sampler::AbstractSampler = SampleFromPrior(),
ctx::DynamicPPL.AbstractContext = DynamicPPL.DefaultContext()
)
T = typeof(getlogp(vi))

# Specify objective function.
function f(θ)
new_vi = VarInfo(vi, sampler, θ)
model(new_vi, sampler)
model(new_vi, sampler, ctx)
return getlogp(new_vi)
end

Expand Down
34 changes: 32 additions & 2 deletions src/modes/ModeEstimation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,32 @@ function (f::OptimLogDensity)(z)
return -DynamicPPL.getlogp(varinfo)
end

function (f::OptimLogDensity)(F, G, z)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if it's useful to keep this separate definition? It seems we only need f(F, G, H, z), so the implementation could just be included there directly.

spl = DynamicPPL.SampleFromPrior()

# Calculate log joint and the gradient
l, g = gradient_logp(
z,
DynamicPPL.VarInfo(f.vi, spl, z),
f.model,
DynamicPPL.SampleFromPrior(),
f.context
)

if G !== nothing
# Use the negative gradient because we are minimizing.
G[:] = -g
end

if F !== nothing
# Return the negative log joint because we are minimizing.
F = -l
return F
end

return nothing
end

"""
ModeResult{
V<:NamedArrays.NamedArray,
Expand Down Expand Up @@ -369,6 +395,11 @@ function _optimize(
args...;
kwargs...
)
# Throw an error if we received a second-order optimizer.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have to do that? Doesn't Optim just use ForwardDiff (or FD?) to compute the Hessian in this case? If that's the case, then we shouldn't throw an error IMO. It might not be the most efficient approach and would not adhere to the user-provided AD settings but as long as it works we could only print a warning.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In FD yes; but (for example in the project that I am working on) it could be that users only define custom adjoints for the gradients but not the Hessian. Therefore even the user provides an AD backend, it might not be a great idea if it by default take that for Hessian function.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean we shouldn't even print a warning? Would be fine with me as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I think throwing an error when some Hessian-required optimizer is received is a great idea, just like what Cameron did here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we want to throw an error if the Hessian is evaluated, I suggest using only_fgh!(f) and implementing f(F, G, H, x) that contains the check

if H !== nothing
    error("second order methods are not supported at the moment")
end

In general, this approach is more flexible, avoids baking in a hardcoded check for a special type of a different package in our implementation, and avoids incorrect and unexpected behaviour for second-order optimization algorithms that don't subtype this specific type (since multiple inheritance is not possible in Julia, that's not an impossible scenario per se).

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a bug. I think there might be an issue for it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just found JuliaNLSolvers/Optim.jl#718, I guess that's the related issue.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I have a fix. Sorry to cossio for waiting a year and a half 😬

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean, I will tag a fix in an hour or so, so please don't special case with a branch.

Copy link

@pkofod pkofod Aug 7, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if optimizer isa Optim.SecondOrderOptimizer
throw(ArgumentError("Second order optimizers for MLE/MAP are not yet supported."))
end

# Do some initialization.
spl = DynamicPPL.SampleFromPrior()

Expand All @@ -378,9 +409,8 @@ function _optimize(
link!(f.vi, spl)
init_vals = f.vi[spl]


# Optimize!
M = Optim.optimize(f, init_vals, optimizer, options, args...; kwargs...)
M = Optim.optimize(Optim.only_fg!(f), init_vals, optimizer, options, args...; kwargs...)

# Warn the user if the optimization did not converge.
if !Optim.converged(M)
Expand Down
14 changes: 5 additions & 9 deletions test/modes/ModeEstimation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,17 @@ include(dir*"/test/test_utils/AllUtils.jl")
@testset "ModeEstimation.jl" begin
@testset "MLE" begin
Random.seed!(222)
true_value = [0.0625031, 1.75]
true_value = [0.0625, 1.75]

m1 = optimize(gdemo_default, MLE())
m2 = optimize(gdemo_default, MLE(), NelderMead())
m3 = optimize(gdemo_default, MLE(), Newton())
m4 = optimize(gdemo_default, MLE(), true_value, Newton())
m5 = optimize(gdemo_default, MLE(), true_value)
m3 = optimize(gdemo_default, MLE(), true_value, LBFGS())
m4 = optimize(gdemo_default, MLE(), true_value)

@test all(isapprox.(m1.values.array - true_value, 0.0, atol=0.01))
@test all(isapprox.(m2.values.array - true_value, 0.0, atol=0.01))
@test all(isapprox.(m3.values.array - true_value, 0.0, atol=0.01))
@test all(isapprox.(m4.values.array - true_value, 0.0, atol=0.01))
@test all(isapprox.(m5.values.array - true_value, 0.0, atol=0.01))
end

@testset "MAP" begin
Expand All @@ -34,15 +32,13 @@ include(dir*"/test/test_utils/AllUtils.jl")

m1 = optimize(gdemo_default, MAP())
m2 = optimize(gdemo_default, MAP(), NelderMead())
m3 = optimize(gdemo_default, MAP(), Newton())
m4 = optimize(gdemo_default, MAP(), true_value, Newton())
m5 = optimize(gdemo_default, MAP(), true_value)
m3 = optimize(gdemo_default, MAP(), true_value, LBFGS())
m4 = optimize(gdemo_default, MAP(), true_value)

@test all(isapprox.(m1.values.array - true_value, 0.0, atol=0.01))
@test all(isapprox.(m2.values.array - true_value, 0.0, atol=0.01))
@test all(isapprox.(m3.values.array - true_value, 0.0, atol=0.01))
@test all(isapprox.(m4.values.array - true_value, 0.0, atol=0.01))
@test all(isapprox.(m5.values.array - true_value, 0.0, atol=0.01))
end

@testset "StatsBase integration" begin
Expand Down