JuliaGaussianProcesses / JuliaGaussianProcesses/ParameterHandling.jl

Using flatten/unflatten for Automatic Differentiation

Open
#27 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Julia
Stars
74
Forks
10
PR merge metrics
No merged PRs in 30d

Description

Hi there,

Really nice package!

I was wondering if one can adjust the flatten/unflatten functions, such that unflatten is also working inside a closure for using Automatic Differentation.

At the moment, it seems that the type constraints cannot handle Duals. MWE:

using ParameterHandling, Distributions, ReverseDiff, ForwardDiff

# Get sample data and parameter
val = ( μ = 1., σ = 2. )
data = randn(100)

# Write down a logdensity with parameter and data as arguments
function log_density(val, data)
        return sum( Distributions.logpdf(Distributions.Normal(val.μ, val.σ), data[iter] ) for iter in eachindex(data) )
end
log_density(val, data)

# Closure for transforming θ Vector to NamedTuple
function get_log_target(val, data)
        _, unflatten = ParameterHandling.flatten(val)
        function log_target(θ::AbstractVector{T}) where T
                return log_density( unflatten(θ), data)
        end
end

# Check if it is working
lt = get_log_target(val, data)
theta = [.1, .2]
lt(theta)

# Method Error for Dual numbers
ForwardDiff.gradient(lt, theta) # MethodError: no method matching (::ParameterHandling.var"#unflatten_to_NamedTuple#15...
ReverseDiff.gradient(lt, theta) # MethodError: no method matching (::ParameterHandling.var"#unflatten_to_NamedTuple#15"{Float64, NamedTuple{(:μ, :σ)

Zygote was actually working for this toy example, but breaks when used with more complex examples (and was not very fast).

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the flatten/unflatten implementation and reproduce the supplied MWE with ForwardDiff.gradient and ReverseDiff.gradient. Trace the type constraints involved when unflatten is called inside log_target; done means both gradient calls work for the closure without the reported MethodError.

Written by the indexing model from the issue text.

Assessment

Tech stack
julia
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.