-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathModeEstimation.jl
337 lines (259 loc) · 9.66 KB
/
ModeEstimation.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
module ModeEstimation
using ..Turing
using Bijectors
using Random
using SciMLBase: OptimizationFunction, OptimizationProblem, AbstractADType, NoAD
using DynamicPPL
using DynamicPPL: Model, AbstractContext, VarInfo, VarName,
_getindex, getsym, getfield, settrans!, setorder!,
get_and_set_val!, istrans
export constrained_space,
MAP,
MLE,
OptimLogDensity,
OptimizationContext,
get_parameter_bounds,
optim_objective,
optim_function,
optim_problem
struct constrained_space{x} end
struct MLE end
struct MAP end
"""
OptimizationContext{C<:AbstractContext} <: AbstractContext
The `OptimizationContext` transforms variables to their constrained space, but
does not use the density with respect to the transformation. This context is
intended to allow an optimizer to sample in R^n freely.
"""
struct OptimizationContext{C<:AbstractContext} <: AbstractContext
context::C
end
DynamicPPL.NodeTrait(::OptimizationContext) = DynamicPPL.IsParent()
DynamicPPL.childcontext(context::OptimizationContext) = context.context
DynamicPPL.setchildcontext(::OptimizationContext, child) = OptimizationContext(child)
# assume
function DynamicPPL.tilde_assume(rng::Random.AbstractRNG, ctx::OptimizationContext, spl, dist, vn, vi)
return DynamicPPL.tilde_assume(ctx, spl, dist, vn, vi)
end
function DynamicPPL.tilde_assume(ctx::OptimizationContext{<:LikelihoodContext}, spl, dist, vn, vi)
r = vi[vn]
return r, 0, vi
end
function DynamicPPL.tilde_assume(ctx::OptimizationContext, spl, dist, vn, vi)
r = vi[vn]
return r, Distributions.logpdf(dist, r), vi
end
# dot assume
function DynamicPPL.dot_tilde_assume(rng::Random.AbstractRNG, ctx::OptimizationContext, sampler, right, left, vns, vi)
return DynamicPPL.dot_tilde_assume(ctx, sampler, right, left, vns, vi)
end
function DynamicPPL.dot_tilde_assume(ctx::OptimizationContext{<:LikelihoodContext}, sampler::SampleFromPrior, right, left, vns, vi)
# Values should be set and we're using `SampleFromPrior`, hence the `rng` argument shouldn't
# affect anything.
r = DynamicPPL.get_and_set_val!(Random.GLOBAL_RNG, vi, vns, right, sampler)
return r, 0, vi
end
function DynamicPPL.dot_tilde_assume(ctx::OptimizationContext, sampler::SampleFromPrior, right, left, vns, vi)
# Values should be set and we're using `SampleFromPrior`, hence the `rng` argument shouldn't
# affect anything.
r = DynamicPPL.get_and_set_val!(Random.GLOBAL_RNG, vi, vns, right, sampler)
return r, loglikelihood(right, r), vi
end
"""
OptimLogDensity{M<:Model,C<:Context,V<:VarInfo}
A struct that stores the log density function of a `DynamicPPL` model.
"""
struct OptimLogDensity{M<:Model,C<:AbstractContext,V<:VarInfo}
"A `DynamicPPL.Model` constructed either with the `@model` macro or manually."
model::M
"A `DynamicPPL.AbstractContext` used to evaluate the model. `LikelihoodContext` or `DefaultContext` are typical for MAP/MLE."
context::C
"A `DynamicPPL.VarInfo` struct that will be used to update model parameters."
vi::V
end
"""
OptimLogDensity(model::Model, context::AbstractContext)
Create a callable `OptimLogDensity` struct that evaluates a model using the given `context`.
"""
function OptimLogDensity(model::Model, context::AbstractContext)
init = VarInfo(model)
return OptimLogDensity(model, context, init)
end
"""
(f::OptimLogDensity)(z)
Evaluate the log joint (with `DefaultContext`) or log likelihood (with `LikelihoodContext`)
at the array `z`.
"""
function (f::OptimLogDensity)(z)
spl = DynamicPPL.SampleFromPrior()
varinfo = DynamicPPL.VarInfo(f.vi, spl, z)
f.model(varinfo, spl, f.context)
return -DynamicPPL.getlogp(varinfo)
end
function (f::OptimLogDensity)(F, G, H, z)
# Throw an error if a second order method was used.
if H !== nothing
error("Second order optimization is not yet supported.")
end
spl = DynamicPPL.SampleFromPrior()
if G !== nothing
# Calculate log joint and the gradient
l, g = Turing.gradient_logp(
z,
DynamicPPL.VarInfo(f.vi, spl, z),
f.model,
spl,
f.context
)
# Use the negative gradient because we are minimizing.
G[:] = -g
# If F is something, return that since we already have the
# log joint.
if F !== nothing
F = -l
return F
end
end
# No gradient necessary, just return the log joint.
if F !== nothing
F = f(z)
return F
end
return nothing
end
#################################################
# Generic optimisation objective initialisation #
#################################################
function transform!(f::OptimLogDensity)
spl = DynamicPPL.SampleFromPrior()
## Check link status of vi in OptimLogDensity
linked = DynamicPPL.islinked(f.vi, spl)
## transform into constrained or unconstrained space depending on current state of vi
if !linked
DynamicPPL.link!(f.vi, spl)
else
DynamicPPL.invlink!(f.vi, spl)
end
return nothing
end
function transform!(p::AbstractArray, vi::DynamicPPL.VarInfo, ::constrained_space{true})
spl = DynamicPPL.SampleFromPrior()
linked = DynamicPPL.islinked(vi, spl)
# !linked && DynamicPPL.link!(vi, spl)
!linked && return identity(p)
vi[spl] = p
DynamicPPL.invlink!(vi,spl)
p .= vi[spl]
linked && DynamicPPL.link!(vi,spl)
return nothing
end
function transform!(p::AbstractArray, vi::DynamicPPL.VarInfo, ::constrained_space{false})
spl = DynamicPPL.SampleFromPrior()
linked = DynamicPPL.islinked(vi, spl)
linked && DynamicPPL.invlink!(vi, spl)
vi[spl] = p
DynamicPPL.link!(vi, spl)
p .= vi[spl]
!linked && DynamicPPL.invlink!(vi, spl)
return nothing
end
function transform(p::AbstractArray, vi::DynamicPPL.VarInfo, con::constrained_space)
tp = copy(p)
transform!(tp, vi, con)
return tp
end
abstract type AbstractTransform end
struct ParameterTransform{T<:DynamicPPL.VarInfo, S<:constrained_space} <: AbstractTransform
vi::T
space::S
end
struct Init{T<:DynamicPPL.VarInfo, S<:constrained_space} <: AbstractTransform
vi::T
space::S
end
function (t::AbstractTransform)(p::AbstractArray)
return transform(p, t.vi, t.space)
end
function (t::Init)()
return t.vi[DynamicPPL.SampleFromPrior()]
end
function get_parameter_bounds(model::DynamicPPL.Model)
vi = DynamicPPL.VarInfo(model)
spl = DynamicPPL.SampleFromPrior()
## Check link status of vi
linked = DynamicPPL.islinked(vi, spl)
## transform into unconstrained
!linked && DynamicPPL.link!(vi, spl)
lb = transform(fill(-Inf,length(vi[DynamicPPL.SampleFromPrior()])), vi, constrained_space{true}())
ub = transform(fill(Inf,length(vi[DynamicPPL.SampleFromPrior()])), vi, constrained_space{true}())
return lb, ub
end
function _optim_objective(model::DynamicPPL.Model, ::MAP, ::constrained_space{false})
ctx = OptimizationContext(DynamicPPL.DefaultContext())
obj = OptimLogDensity(model, ctx)
transform!(obj)
init = Init(obj.vi, constrained_space{false}())
t = ParameterTransform(obj.vi, constrained_space{true}())
return (obj=obj, init = init, transform=t)
end
function _optim_objective(model::DynamicPPL.Model, ::MAP, ::constrained_space{true})
ctx = OptimizationContext(DynamicPPL.DefaultContext())
obj = OptimLogDensity(model, ctx)
init = Init(obj.vi, constrained_space{true}())
t = ParameterTransform(obj.vi, constrained_space{true}())
return (obj=obj, init = init, transform=t)
end
function _optim_objective(model::DynamicPPL.Model, ::MLE, ::constrained_space{false})
ctx = OptimizationContext(DynamicPPL.LikelihoodContext())
obj = OptimLogDensity(model, ctx)
transform!(obj)
init = Init(obj.vi, constrained_space{false}())
t = ParameterTransform(obj.vi, constrained_space{true}())
return (obj=obj, init = init, transform=t)
end
function _optim_objective(model::DynamicPPL.Model, ::MLE, ::constrained_space{true})
ctx = OptimizationContext(DynamicPPL.LikelihoodContext())
obj = OptimLogDensity(model, ctx)
init = Init(obj.vi, constrained_space{true}())
t = ParameterTransform(obj.vi, constrained_space{true}())
return (obj=obj, init = init, transform=t)
end
function optim_objective(model::DynamicPPL.Model, estimator::Union{MLE, MAP}; constrained::Bool=true)
return _optim_objective(model, estimator, constrained_space{constrained}())
end
function optim_function(
model::Model,
estimator::Union{MLE, MAP};
constrained::Bool=true,
autoad::Union{Nothing, AbstractADType}=NoAD(),
)
if autoad === nothing
Base.depwarn("the use of `autoad=nothing` is deprecated, please use `autoad=SciMLBase.NoAD()`", :optim_function)
end
obj, init, t = optim_objective(model, estimator; constrained=constrained)
l(x, _) = obj(x)
f = if autoad isa AbstractADType && autoad !== NoAD()
OptimizationFunction(l, autoad)
else
OptimizationFunction(
l;
grad = (G,x,p) -> obj(nothing, G, nothing, x),
hess = (H,x,p) -> obj(nothing, nothing, H, x),
)
end
return (func=f, init=init, transform = t)
end
function optim_problem(
model::Model,
estimator::Union{MAP, MLE};
constrained::Bool=true,
init_theta=nothing,
autoad::Union{Nothing, AbstractADType}=NoAD(),
kwargs...,
)
f, init, transform = optim_function(model, estimator; constrained=constrained, autoad=autoad)
u0 = init_theta === nothing ? init() : init(init_theta)
prob = OptimizationProblem(f, u0; kwargs...)
return (; prob, init, transform)
end
end