Skip to content
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

Unify transition also in external samplers #2030

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
13 changes: 6 additions & 7 deletions src/inference/Inference.jl
Original file line number Diff line number Diff line change
Expand Up @@ -123,19 +123,20 @@ end
######################
# Default Transition #
######################
# Default
# Extended in contrib/inference/abstractmcmc.jl
getstats(t) = nothing

struct Transition{T, F<:AbstractFloat, S<:Union{NamedTuple, Nothing}}
θ :: T
lp :: F # TODO: merge `lp` with `stat`
stat :: S
end

Transition(θ, lp) = Transition(θ, lp, nothing)
yebai marked this conversation as resolved.
Show resolved Hide resolved

function Transition(vi::AbstractVarInfo; nt::NamedTuple=NamedTuple())
function Transition(vi::AbstractVarInfo, t=nothing; nt::NamedTuple=NamedTuple())
θ = merge(tonamedtuple(vi), nt)
lp = getlogp(vi)
return Transition(θ, lp, nothing)
return Transition(θ, lp, getstats(t))
end

function metadata(t::Transition)
Expand Down Expand Up @@ -664,9 +665,7 @@ function transitions_from_chain(
model(rng, vi, sampler)

# Convert `VarInfo` into `NamedTuple` and save.
theta = DynamicPPL.tonamedtuple(vi)
lp = Turing.getlogp(vi)
Transition(theta, lp)
Transition(vi)
end

return transitions
Expand Down