TuringLang / AbstractPPL.jl

Common types and interfaces for probabilistic programming
http://turinglang.org/AbstractPPL.jl/
MIT License
27 stars 7 forks source link

Supporting mutating node values in `GraphInfo` #51

Closed yebai closed 2 years ago

yebai commented 2 years ago

Our current GraphInfo stores GraphInfo.value in a NamedTuple which prevents mutation.

https://github.com/TuringLang/AbstractPPL.jl/blob/469252618fd6ea85dc911b0999b4614fcca45f2f/src/graphinfo.jl#L25

One simple improvement is to use Ref to store values inside NamedTupe. It does not influence type stability and keep the overall design intact. For example:

julia> Model(
               s2 = (0.0, () -> InverseGamma(2.0,3.0), :Stochastic), 
               μ = (1.0, () -> 1.0, :Logical), 
               y = (0.0, (μ, s2) -> MvNormal(μ, sqrt(s2)), :Stochastic)
           )

becomes

julia> Model(
               s2 = (Ref(0.0), () -> InverseGamma(2.0,3.0), :Stochastic), 
               μ = (Ref(1.0), () -> 1.0, :Logical), 
               y = (Ref(0.0), (μ, s2) -> MvNormal(μ, sqrt(s2)), :Stochastic)
           )

Then we can do

# support mutation for stochastic variables
m[@varname s2] = 5.0 

# this should result in an error since we can't mutate logical variables (and hyperparameters)
m[@varname μ] = 2.0 

Note that we only need to change the internal model constructor and accessor functions and keep the user-facing Model constructor the same.

yebai commented 2 years ago

Fixed by #57