-
Notifications
You must be signed in to change notification settings - Fork 226
/
Copy pathVariationalInference.jl
171 lines (147 loc) · 5.21 KB
/
VariationalInference.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
module Variational
using DynamicPPL
using ADTypes
using Distributions
using LinearAlgebra
using LogDensityProblems
using Random
using UnicodePlots
import ..Turing: DEFAULT_ADTYPE, PROGRESS
import AdvancedVI
import Bijectors
# Reexports
using AdvancedVI: RepGradELBO, ScoreGradELBO, DoG, DoWG
export vi, RepGradELBO, ScoreGradELBO, DoG, DoWG
export meanfield_gaussian, fullrank_gaussian
include("bijectors.jl")
function make_logdensity(model::DynamicPPL.Model)
weight = 1.0
ctx = DynamicPPL.MiniBatchContext(DynamicPPL.DefaultContext(), weight)
return DynamicPPL.LogDensityFunction(model, DynamicPPL.VarInfo(model), ctx)
end
function initialize_gaussian_scale(
rng::Random.AbstractRNG,
model::DynamicPPL.Model,
location::AbstractVector,
scale::AbstractMatrix;
num_samples::Int=10,
num_max_trials::Int=10,
reduce_factor=one(eltype(scale)) / 2,
)
prob = make_logdensity(model)
ℓπ = Base.Fix1(LogDensityProblems.logdensity, prob)
varinfo = DynamicPPL.VarInfo(model)
n_trial = 0
while true
q = AdvancedVI.MvLocationScale(location, scale, Normal())
b = Bijectors.bijector(model; varinfo=varinfo)
q_trans = Bijectors.transformed(q, Bijectors.inverse(b))
energy = mean(ℓπ, eachcol(rand(rng, q_trans, num_samples)))
if isfinite(energy)
return scale
elseif n_trial == num_max_trials
error("Could not find an initial")
end
scale = reduce_factor * scale
n_trial += 1
end
end
function meanfield_gaussian(
rng::Random.AbstractRNG,
model::DynamicPPL.Model,
location::Union{Nothing,<:AbstractVector}=nothing,
scale::Union{Nothing,<:Diagonal}=nothing;
kwargs...,
)
varinfo = DynamicPPL.VarInfo(model)
# Use linked `varinfo` to determine the correct number of parameters.
# TODO: Replace with `length` once this is implemented for `VarInfo`.
varinfo_linked = DynamicPPL.link(varinfo, model)
num_params = length(varinfo_linked[:])
μ = if isnothing(location)
zeros(num_params)
else
@assert length(location) == num_params "Length of the provided location vector, $(length(location)), does not match dimension of the target distribution, $(num_params)."
location
end
L = if isnothing(scale)
initialize_gaussian_scale(rng, model, μ, Diagonal(ones(num_params)); kwargs...)
else
@assert size(scale) == (num_params, num_params) "Dimensions of the provided scale matrix, $(size(scale)), does not match the dimension of the target distribution, $(num_params)."
L = scale
end
q = AdvancedVI.MeanFieldGaussian(μ, L)
b = Bijectors.bijector(model; varinfo=varinfo)
return Bijectors.transformed(q, Bijectors.inverse(b))
end
function meanfield_gaussian(
model::DynamicPPL.Model,
location::Union{Nothing,<:AbstractVector}=nothing,
scale::Union{Nothing,<:Diagonal}=nothing;
kwargs...,
)
return meanfield_gaussian(Random.default_rng(), model, location, scale; kwargs...)
end
function fullrank_gaussian(
rng::Random.AbstractRNG,
model::DynamicPPL.Model,
location::Union{Nothing, <:AbstractVector} = nothing,
scale::Union{Nothing, <:LowerTriangular} = nothing;
kwargs...
)
varinfo = DynamicPPL.VarInfo(model)
# Use linked `varinfo` to determine the correct number of parameters.
# TODO: Replace with `length` once this is implemented for `VarInfo`.
varinfo_linked = DynamicPPL.link(varinfo, model)
num_params = length(varinfo_linked[:])
μ = if isnothing(location)
zeros(num_params)
else
@assert length(location) == num_params "Length of the provided location vector, $(length(location)), does not match dimension of the target distribution, $(num_params)."
location
end
L = if isnothing(scale)
L0 = LowerTriangular(Matrix{Float64}(I, num_params, num_params))
initialize_gaussian_scale(rng, model, μ, L0; kwargs...)
else
@assert size(scale) == (num_params, num_params) "Dimensions of the provided scale matrix, $(size(scale)), does not match the dimension of the target distribution, $(num_params)."
scale
end
q = AdvancedVI.FullRankGaussian(μ, L)
b = Bijectors.bijector(model; varinfo=varinfo)
return Bijectors.transformed(q, Bijectors.inverse(b))
end
function fullrank_gaussian(
model::DynamicPPL.Model,
location::Union{Nothing,<:AbstractVector}=nothing,
scale::Union{Nothing,<:Diagonal}=nothing;
kwargs...,
)
return fullrank_gaussian(Random.default_rng(), model, location, scale; kwargs...)
end
function vi(
model::DynamicPPL.Model,
q::Bijectors.TransformedDistribution,
n_iterations::Int;
objective=RepGradELBO(10; entropy=AdvancedVI.ClosedFormEntropyZeroGradient()),
show_progress::Bool=PROGRESS[],
optimizer=AdvancedVI.DoWG(),
averager=AdvancedVI.PolynomialAveraging(),
operator=AdvancedVI.ProximalLocationScaleEntropy(),
adtype::ADTypes.AbstractADType=DEFAULT_ADTYPE,
kwargs...
)
return AdvancedVI.optimize(
make_logdensity(model),
objective,
q,
n_iterations;
show_progress=show_progress,
adtype,
optimizer,
averager,
operator,
kwargs...
)
end
end