|
| 1 | +""" |
| 2 | + GibbsConditional(get_cond_dists) |
| 3 | +
|
| 4 | +A Gibbs component sampler that samples variables according to user-provided analytical |
| 5 | +conditional posterior distributions. |
| 6 | +
|
| 7 | +When using Gibbs sampling, sometimes one may know the analytical form of the posterior for |
| 8 | +a given variable, given the conditioned values of the other variables. In such cases one can |
| 9 | +use `GibbsConditional` as a component sampler to to sample from these known conditionals |
| 10 | +directly, avoiding any MCMC methods. One does so with |
| 11 | +
|
| 12 | +```julia |
| 13 | +sampler = Gibbs( |
| 14 | + (@varname(var1), @varname(var2)) => GibbsConditional(get_cond_dists), |
| 15 | + other samplers go here... |
| 16 | +) |
| 17 | +``` |
| 18 | +
|
| 19 | +Here `get_cond_dists(c::Dict{<:VarName})` should be a function that takes a `Dict` mapping |
| 20 | +the conditioned variables (anything other than `var1` and `var2`) to their values, and |
| 21 | +returns the conditional posterior distributions for `var1` and `var2`. You may, of course, |
| 22 | +have any number of variables being sampled as a block in this manner, we only use two as an |
| 23 | +example. The return value of `get_cond_dists` should be one of the following: |
| 24 | +- A single `Distribution`, if only one variable is being sampled. |
| 25 | +- An `AbstractDict{<:VarName,<:Distribution}` that maps the variables being sampled to their |
| 26 | + conditional posteriors E.g. `Dict(@varname(var1) => dist1, @varname(var2) => dist2)`. |
| 27 | +- A `NamedTuple` of `Distribution`s, which is like the `AbstractDict` case but can be used |
| 28 | + if all the variable names are single `Symbol`s, and may be more performant. E.g. |
| 29 | + `(; var1=dist1, var2=dist2)`. |
| 30 | +
|
| 31 | +# Examples |
| 32 | +
|
| 33 | +```julia |
| 34 | +# Define a model |
| 35 | +@model function inverse_gdemo(x) |
| 36 | + precision ~ Gamma(2, inv(3)) |
| 37 | + std = sqrt(1 / precision) |
| 38 | + m ~ Normal(0, std) |
| 39 | + for i in eachindex(x) |
| 40 | + x[i] ~ Normal(m, std) |
| 41 | + end |
| 42 | +end |
| 43 | +
|
| 44 | +# Define analytical conditionals. See |
| 45 | +# https://en.wikipedia.org/wiki/Conjugate_prior#When_likelihood_function_is_a_continuous_distribution |
| 46 | +function cond_precision(c) |
| 47 | + a = 2.0 |
| 48 | + b = 3.0 |
| 49 | + # We use AbstractPPL.getvalue instead of indexing into `c` directly to guard against |
| 50 | + # issues where e.g. you try to get `c[@varname(x[1])]` but only `@varname(x)` is present |
| 51 | + # in `c`. `getvalue` handles that gracefully, `getindex` doesn't. In this case |
| 52 | + # `getindex` would suffice, but `getvalue` is good practice. |
| 53 | + m = AbstractPPL.getvalue(c, @varname(m)) |
| 54 | + x = AbstractPPL.getvalue(c, @varname(x)) |
| 55 | + n = length(x) |
| 56 | + a_new = a + (n + 1) / 2 |
| 57 | + b_new = b + sum(abs2, x .- m) / 2 + m^2 / 2 |
| 58 | + return Gamma(a_new, 1 / b_new) |
| 59 | +end |
| 60 | +
|
| 61 | +function cond_m(c) |
| 62 | + precision = AbstractPPL.getvalue(c, @varname(precision)) |
| 63 | + x = AbstractPPL.getvalue(c, @varname(x)) |
| 64 | + n = length(x) |
| 65 | + m_mean = sum(x) / (n + 1) |
| 66 | + m_var = 1 / (precision * (n + 1)) |
| 67 | + return Normal(m_mean, sqrt(m_var)) |
| 68 | +end |
| 69 | +
|
| 70 | +# Sample using GibbsConditional |
| 71 | +model = inverse_gdemo([1.0, 2.0, 3.0]) |
| 72 | +chain = sample(model, Gibbs( |
| 73 | + :precision => GibbsConditional(cond_precision), |
| 74 | + :m => GibbsConditional(cond_m) |
| 75 | +), 1000) |
| 76 | +``` |
| 77 | +""" |
| 78 | +struct GibbsConditional{C} <: AbstractSampler |
| 79 | + get_cond_dists::C |
| 80 | +end |
| 81 | + |
| 82 | +isgibbscomponent(::GibbsConditional) = true |
| 83 | + |
| 84 | +""" |
| 85 | + build_variable_dict(model::DynamicPPL.Model) |
| 86 | +
|
| 87 | +Traverse the context stack of `model` and build a `Dict` of all the variable values that are |
| 88 | +set in GibbsContext, ConditionContext, or FixedContext. |
| 89 | +""" |
| 90 | +function build_variable_dict(model::DynamicPPL.Model) |
| 91 | + context = model.context |
| 92 | + cond_vals = DynamicPPL.conditioned(context) |
| 93 | + fixed_vals = DynamicPPL.fixed(context) |
| 94 | + # TODO(mhauru) Can we avoid invlinking all the time? |
| 95 | + global_vi = DynamicPPL.invlink(get_gibbs_global_varinfo(context), model) |
| 96 | + # TODO(mhauru) This creates a lot of Dicts, which are then immediately merged into one. |
| 97 | + # Also, DynamicPPL.to_varname_dict is known to be inefficient. Make a more efficient |
| 98 | + # implementation. |
| 99 | + return merge( |
| 100 | + DynamicPPL.values_as(global_vi, Dict), |
| 101 | + DynamicPPL.to_varname_dict(cond_vals), |
| 102 | + DynamicPPL.to_varname_dict(fixed_vals), |
| 103 | + DynamicPPL.to_varname_dict(model.args), |
| 104 | + ) |
| 105 | +end |
| 106 | + |
| 107 | +function get_gibbs_global_varinfo(context::DynamicPPL.AbstractContext) |
| 108 | + return if context isa GibbsContext |
| 109 | + get_global_varinfo(context) |
| 110 | + elseif DynamicPPL.NodeTrait(context) isa DynamicPPL.IsParent |
| 111 | + get_gibbs_global_varinfo(DynamicPPL.childcontext(context)) |
| 112 | + else |
| 113 | + msg = """No GibbsContext found in context stack. Are you trying to use \ |
| 114 | + GibbsConditional outside of Gibbs? |
| 115 | + """ |
| 116 | + throw(ArgumentError(msg)) |
| 117 | + end |
| 118 | +end |
| 119 | + |
| 120 | +function initialstep( |
| 121 | + ::Random.AbstractRNG, |
| 122 | + model::DynamicPPL.Model, |
| 123 | + ::GibbsConditional, |
| 124 | + vi::DynamicPPL.AbstractVarInfo; |
| 125 | + kwargs..., |
| 126 | +) |
| 127 | + state = DynamicPPL.is_transformed(vi) ? DynamicPPL.invlink(vi, model) : vi |
| 128 | + # Since GibbsConditional is only used within Gibbs, it does not need to return a |
| 129 | + # transition. |
| 130 | + return nothing, state |
| 131 | +end |
| 132 | + |
| 133 | +function AbstractMCMC.step( |
| 134 | + rng::Random.AbstractRNG, |
| 135 | + model::DynamicPPL.Model, |
| 136 | + sampler::GibbsConditional, |
| 137 | + state::DynamicPPL.AbstractVarInfo; |
| 138 | + kwargs..., |
| 139 | +) |
| 140 | + # Get all the conditioned variable values from the model context. This is assumed to |
| 141 | + # include a GibbsContext as part of the context stack. |
| 142 | + condvals = build_variable_dict(model) |
| 143 | + conddists = sampler.get_cond_dists(condvals) |
| 144 | + |
| 145 | + # We support three different kinds of return values for `sample.get_cond_dists`, to make |
| 146 | + # life easier for the user. |
| 147 | + if conddists isa AbstractDict |
| 148 | + for (vn, dist) in conddists |
| 149 | + state = setindex!!(state, rand(rng, dist), vn) |
| 150 | + end |
| 151 | + elseif conddists isa NamedTuple |
| 152 | + for (vn_sym, dist) in pairs(conddists) |
| 153 | + vn = VarName{vn_sym}() |
| 154 | + state = setindex!!(state, rand(rng, dist), vn) |
| 155 | + end |
| 156 | + else |
| 157 | + # Single variable case |
| 158 | + vn = only(keys(state)) |
| 159 | + state = setindex!!(state, rand(rng, conddists), vn) |
| 160 | + end |
| 161 | + |
| 162 | + # Since GibbsConditional is only used within Gibbs, it does not need to return a |
| 163 | + # transition. |
| 164 | + return nothing, state |
| 165 | +end |
| 166 | + |
| 167 | +function setparams_varinfo!!( |
| 168 | + ::DynamicPPL.Model, ::GibbsConditional, ::Any, params::DynamicPPL.AbstractVarInfo |
| 169 | +) |
| 170 | + return params |
| 171 | +end |
0 commit comments