Skip to content

Unify transition also in external samplers #2030

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 12 commits into from
Jul 10, 2023
17 changes: 1 addition & 16 deletions src/contrib/inference/abstractmcmc.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,13 @@ struct TuringState{S,F}
logdensity::F
end

struct TuringTransition{T,NT<:NamedTuple,F<:AbstractFloat}
θ::T
lp::F
stat::NT
end

function TuringTransition(vi::AbstractVarInfo, t)
theta = tonamedtuple(vi)
lp = getlogp(vi)
return TuringTransition(theta, lp, getstats(t))
end

metadata(t::TuringTransition) = merge((lp = t.lp,), t.stat)
DynamicPPL.getlogp(t::TuringTransition) = t.lp

state_to_turing(f::DynamicPPL.LogDensityFunction, state) = TuringState(state, f)
function transition_to_turing(f::DynamicPPL.LogDensityFunction, transition)
θ = getparams(transition)
varinfo = DynamicPPL.unflatten(f.varinfo, θ)
# TODO: `deepcopy` is overkill; make more efficient.
varinfo = DynamicPPL.invlink!!(deepcopy(varinfo), f.model)
return TuringTransition(varinfo, transition)
return Transition(varinfo, transition)
end

# NOTE: Only thing that depends on the underlying sampler.
Expand Down
6 changes: 6 additions & 0 deletions src/inference/Inference.jl
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,12 @@ struct Transition{T, F<:AbstractFloat, S<:Union{NamedTuple, Nothing}}
stat :: S
end

function Transition(vi::AbstractVarInfo, t)
theta = tonamedtuple(vi)
lp = getlogp(vi)
return Transition(theta, lp, getstats(t))
end

Transition(θ, lp) = Transition(θ, lp, nothing)

function Transition(vi::AbstractVarInfo; nt::NamedTuple=NamedTuple())
Expand Down