/
gibbs.jl
224 lines (187 loc) · 5.6 KB
/
gibbs.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
###
### Gibbs samplers / compositional samplers.
###
"""
isgibbscomponent(alg)
Determine whether algorithm `alg` is allowed as a Gibbs component.
"""
isgibbscomponent(alg) = false
"""
Gibbs(algs...)
Compositional MCMC interface. Gibbs sampling combines one or more
sampling algorithms, each of which samples from a different set of
variables in a model.
Example:
```julia
@model gibbs_example(x) = begin
v1 ~ Normal(0,1)
v2 ~ Categorical(5)
end
```
# Use PG for a 'v2' variable, and use HMC for the 'v1' variable.
# Note that v2 is discrete, so the PG sampler is more appropriate
# than is HMC.
alg = Gibbs(HMC(0.2, 3, :v1), PG(20, :v2))
```
Tips:
- `HMC` and `NUTS` are fast samplers, and can throw off particle-based
methods like Particle Gibbs. You can increase the effectiveness of particle sampling by including
more particles in the particle sampler.
"""
struct Gibbs{space, A<:Tuple} <: InferenceAlgorithm
algs::A # component sampling algorithms
function Gibbs{space, A}(algs::A) where {space, A<:Tuple}
all(isgibbscomponent, algs) || error("all algorithms have to support Gibbs sampling")
return new{space, A}(algs)
end
end
function Gibbs(algs...)
# obtain space of sampling algorithms
space = Tuple(union(getspace.(algs)...))
Gibbs{space, typeof(algs)}(algs)
end
"""
GibbsState{V<:VarInfo, S<:Tuple{Vararg{Sampler}}}
Stores a `VarInfo` for use in sampling, and a `Tuple` of `Samplers` that
the `Gibbs` sampler iterates through for each `step!`.
"""
mutable struct GibbsState{V<:VarInfo, S<:Tuple{Vararg{Sampler}}} <: AbstractSamplerState
vi::V
samplers::S
end
function GibbsState(model::Model, samplers::Tuple{Vararg{Sampler}})
return GibbsState(VarInfo(model), samplers)
end
function Sampler(alg::Gibbs, model::Model, s::Selector)
# sanity check for space
space = getspace(alg)
# create tuple of samplers
i = 0
samplers = map(alg.algs) do _alg
i += 1
if i == 1
prev_alg = alg.algs[end]
else
prev_alg = alg.algs[i-1]
end
rerun = !(_alg isa MH) || prev_alg isa PG || prev_alg isa ESS || prev_alg isa GibbsConditional
selector = Selector(Symbol(typeof(_alg)), rerun)
Sampler(_alg, model, selector)
end
# create a state variable
state = GibbsState(model, samplers)
# create the sampler
info = Dict{Symbol, Any}()
spl = Sampler(alg, info, s, state)
# add Gibbs to gids for all variables
vi = spl.state.vi
for sym in keys(vi.metadata)
vns = getfield(vi.metadata, sym).vns
for vn in vns
# update the gid for the Gibbs sampler
DynamicPPL.updategid!(vi, vn, spl)
# try to store each subsampler's gid in the VarInfo
for local_spl in samplers
DynamicPPL.updategid!(vi, vn, local_spl)
end
end
end
return spl
end
"""
GibbsTransition
Fields:
- `θ`: The parameters for any given sample.
- `lp`: The log pdf for the sample's parameters.
- `transitions`: The transitions of the samplers.
"""
struct GibbsTransition{T,F,S<:AbstractVector}
θ::T
lp::F
transitions::S
end
function GibbsTransition(spl::Sampler{<:Gibbs}, transitions::AbstractVector)
theta = tonamedtuple(spl.state.vi)
lp = getlogp(spl.state.vi)
return GibbsTransition(theta, lp, transitions)
end
function additional_parameters(::Type{<:GibbsTransition})
return [:lp]
end
DynamicPPL.getlogp(t::GibbsTransition) = t.lp
# Initialize the Gibbs sampler.
function AbstractMCMC.sample_init!(
rng::AbstractRNG,
model::Model,
spl::Sampler{<:Gibbs},
N::Integer;
kwargs...
)
# Initialize each local sampler.
for local_spl in spl.state.samplers
AbstractMCMC.sample_init!(rng, model, local_spl, N; kwargs...)
end
end
# Finalize the Gibbs sampler.
function AbstractMCMC.sample_end!(
rng::AbstractRNG,
model::Model,
spl::Sampler{<:Gibbs},
N::Integer;
kwargs...
)
# Finalize each local sampler.
for local_spl in spl.state.samplers
AbstractMCMC.sample_end!(rng, model, local_spl, N; kwargs...)
end
end
# Steps 2
function AbstractMCMC.step!(
rng::AbstractRNG,
model::Model,
spl::Sampler{<:Gibbs},
N::Integer,
transition::Union{Nothing,GibbsTransition};
kwargs...
)
@debug "Gibbs stepping..."
# Iterate through each of the samplers.
transitions = map(enumerate(spl.state.samplers)) do (i, local_spl)
@debug "$(typeof(local_spl)) stepping..."
# Update the sampler's VarInfo.
local_spl.state.vi = spl.state.vi
# Step through the local sampler.
if transition === nothing
trans = AbstractMCMC.step!(rng, model, local_spl, N, nothing; kwargs...)
else
trans = AbstractMCMC.step!(rng, model, local_spl, N, transition.transitions[i];
kwargs...)
end
# After the step, update the master varinfo.
spl.state.vi = local_spl.state.vi
trans
end
return GibbsTransition(spl, transitions)
end
# Do not store transitions of subsamplers
function AbstractMCMC.transitions_init(
transition::GibbsTransition,
::Model,
::Sampler{<:Gibbs},
N::Integer;
kwargs...
)
return Vector{Transition{typeof(transition.θ),typeof(transition.lp)}}(undef, N)
end
function AbstractMCMC.transitions_save!(
transitions::Vector{<:Transition},
iteration::Integer,
transition::GibbsTransition,
::Model,
::Sampler{<:Gibbs},
::Integer;
kwargs...
)
transitions[iteration] = Transition(transition.θ, transition.lp)
return
end