-
Notifications
You must be signed in to change notification settings - Fork 19
Basic rewrite of the package 2023 edition Part II: Location-scale variational families #51
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
yebai
merged 9 commits into
TuringLang:master
from
Red-Portal:rewriting_advancedvi_locscale
Dec 20, 2023
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
b0e9bfa
add location scale family
Red-Portal 830b4a6
refactor switch bijector tests to use locscale, enable ReverseDiff
Red-Portal 9df544d
fix test file name for location-scale plus bijector inference test
Red-Portal ebb55ef
fix wrong testset names, add interface test for VILocationScale
Red-Portal 3b9a07b
fix test parameters for `LocationScale`
Red-Portal 802a83c
fix test for LocationScale with Bijectors
Red-Portal 021fd46
add tests to improve coverage, fix bug for `rand!` with vectors
Red-Portal 1c80dec
rename location scale, fix type ambiguity for `rand`
Red-Portal bbfac2a
remove duplicate type tests for `LocationScale`
Red-Portal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,164 @@ | ||
|
||
""" | ||
MvLocationScale(location, scale, dist) <: ContinuousMultivariateDistribution | ||
|
||
The location scale variational family broadly represents various variational | ||
families using `location` and `scale` variational parameters. | ||
|
||
It generally represents any distribution for which the sampling path can be | ||
represented as follows: | ||
```julia | ||
d = length(location) | ||
u = rand(dist, d) | ||
z = scale*u + location | ||
``` | ||
""" | ||
struct MvLocationScale{ | ||
S, D <: ContinuousDistribution, L | ||
} <: ContinuousMultivariateDistribution | ||
location::L | ||
scale ::S | ||
dist ::D | ||
Red-Portal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
end | ||
|
||
Functors.@functor MvLocationScale (location, scale) | ||
|
||
# Specialization of `Optimisers.destructure` for mean-field location-scale families. | ||
# These are necessary because we only want to extract the diagonal elements of | ||
# `scale <: Diagonal`, which is not the default behavior. Otherwise, forward-mode AD | ||
# is very inefficient. | ||
# begin | ||
struct RestructureMeanField{S <: Diagonal, D, L} | ||
q::MvLocationScale{S, D, L} | ||
end | ||
|
||
function (re::RestructureMeanField)(flat::AbstractVector) | ||
n_dims = div(length(flat), 2) | ||
location = first(flat, n_dims) | ||
scale = Diagonal(last(flat, n_dims)) | ||
MvLocationScale(location, scale, re.q.dist) | ||
end | ||
|
||
function Optimisers.destructure( | ||
q::MvLocationScale{<:Diagonal, D, L} | ||
) where {D, L} | ||
@unpack location, scale, dist = q | ||
flat = vcat(location, diag(scale)) | ||
flat, RestructureMeanField(q) | ||
end | ||
# end | ||
|
||
Base.length(q::MvLocationScale) = length(q.location) | ||
|
||
Base.size(q::MvLocationScale) = size(q.location) | ||
|
||
Base.eltype(::Type{<:MvLocationScale{S, D, L}}) where {S, D, L} = eltype(D) | ||
|
||
function StatsBase.entropy(q::MvLocationScale) | ||
@unpack location, scale, dist = q | ||
n_dims = length(location) | ||
n_dims*convert(eltype(location), entropy(dist)) + first(logabsdet(scale)) | ||
end | ||
|
||
function Distributions.logpdf(q::MvLocationScale, z::AbstractVector{<:Real}) | ||
@unpack location, scale, dist = q | ||
sum(Base.Fix1(logpdf, dist), scale \ (z - location)) - first(logabsdet(scale)) | ||
end | ||
|
||
function Distributions._logpdf(q::MvLocationScale, z::AbstractVector{<:Real}) | ||
@unpack location, scale, dist = q | ||
sum(Base.Fix1(logpdf, dist), scale \ (z - location)) - first(logabsdet(scale)) | ||
end | ||
|
||
function Distributions.rand(q::MvLocationScale) | ||
@unpack location, scale, dist = q | ||
n_dims = length(location) | ||
scale*rand(dist, n_dims) + location | ||
end | ||
|
||
function Distributions.rand( | ||
rng::AbstractRNG, q::MvLocationScale{S, D, L}, num_samples::Int | ||
) where {S, D, L} | ||
@unpack location, scale, dist = q | ||
n_dims = length(location) | ||
scale*rand(rng, dist, n_dims, num_samples) .+ location | ||
end | ||
|
||
# This specialization improves AD performance of the sampling path | ||
function Distributions.rand( | ||
rng::AbstractRNG, q::MvLocationScale{<:Diagonal, D, L}, num_samples::Int | ||
) where {L, D} | ||
@unpack location, scale, dist = q | ||
n_dims = length(location) | ||
scale_diag = diag(scale) | ||
scale_diag.*rand(rng, dist, n_dims, num_samples) .+ location | ||
end | ||
|
||
function Distributions._rand!(rng::AbstractRNG, q::MvLocationScale, x::AbstractVecOrMat{<:Real}) | ||
@unpack location, scale, dist = q | ||
rand!(rng, dist, x) | ||
x[:] = scale*x | ||
return x .+= location | ||
end | ||
|
||
Distributions.mean(q::MvLocationScale) = q.location | ||
|
||
function Distributions.var(q::MvLocationScale) | ||
C = q.scale | ||
Diagonal(C*C') | ||
end | ||
|
||
function Distributions.cov(q::MvLocationScale) | ||
C = q.scale | ||
Hermitian(C*C') | ||
end | ||
|
||
""" | ||
FullRankGaussian(location, scale; check_args = true) | ||
|
||
Construct a Gaussian variational approximation with a dense covariance matrix. | ||
|
||
# Arguments | ||
- `location::AbstractVector{T}`: Mean of the Gaussian. | ||
- `scale::LinearAlgebra.AbstractTriangular{T}`: Cholesky factor of the covariance of the Gaussian. | ||
|
||
# Keyword Arguments | ||
- `check_args`: Check the conditioning of the initial scale (default: `true`). | ||
""" | ||
function FullRankGaussian( | ||
μ::AbstractVector{T}, | ||
L::LinearAlgebra.AbstractTriangular{T}; | ||
check_args::Bool = true | ||
) where {T <: Real} | ||
@assert minimum(diag(L)) > eps(eltype(L)) "Scale must be positive definite" | ||
if check_args && (minimum(diag(L)) < sqrt(eps(eltype(L)))) | ||
@warn "Initial scale is too small (minimum eigenvalue is $(minimum(diag(L)))). This might result in unstable optimization behavior." | ||
end | ||
q_base = Normal{T}(zero(T), one(T)) | ||
MvLocationScale(μ, L, q_base) | ||
end | ||
|
||
""" | ||
MeanFieldGaussian(location, scale; check_args = true) | ||
|
||
Construct a Gaussian variational approximation with a diagonal covariance matrix. | ||
|
||
# Arguments | ||
- `location::AbstractVector{T}`: Mean of the Gaussian. | ||
- `scale::Diagonal{T}`: Diagonal Cholesky factor of the covariance of the Gaussian. | ||
|
||
# Keyword Arguments | ||
- `check_args`: Check the conditioning of the initial scale (default: `true`). | ||
""" | ||
function MeanFieldGaussian( | ||
μ::AbstractVector{T}, | ||
L::Diagonal{T}; | ||
check_args::Bool = true | ||
) where {T <: Real} | ||
@assert minimum(diag(L)) > eps(eltype(L)) "Scale must be a Cholesky factor" | ||
if check_args && (minimum(diag(L)) < sqrt(eps(eltype(L)))) | ||
@warn "Initial scale is too small (minimum eigenvalue is $(minimum(diag(L)))). This might result in unstable optimization behavior." | ||
end | ||
q_base = Normal{T}(zero(T), one(T)) | ||
MvLocationScale(μ, L, q_base) | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
|
||
const PROGRESS = length(ARGS) > 0 && ARGS[1] == "--progress" ? true : false | ||
|
||
using Test | ||
|
||
@testset "inference RepGradELBO VILocationScale" begin | ||
@testset "$(modelname) $(objname) $(realtype) $(adbackname)" for | ||
realtype ∈ [Float64, Float32], | ||
(modelname, modelconstr) ∈ Dict( | ||
:Normal=> normal_meanfield, | ||
:Normal=> normal_fullrank, | ||
), | ||
(objname, objective) ∈ Dict( | ||
:RepGradELBOClosedFormEntropy => RepGradELBO(10), | ||
:RepGradELBOStickingTheLanding => RepGradELBO(10, entropy = StickingTheLandingEntropy()), | ||
), | ||
(adbackname, adbackend) ∈ Dict( | ||
:ForwarDiff => AutoForwardDiff(), | ||
:ReverseDiff => AutoReverseDiff(), | ||
:Zygote => AutoZygote(), | ||
#:Enzyme => AutoEnzyme(), | ||
) | ||
|
||
seed = (0x38bef07cf9cc549d) | ||
rng = StableRNG(seed) | ||
|
||
modelstats = modelconstr(rng, realtype) | ||
@unpack model, μ_true, L_true, n_dims, is_meanfield = modelstats | ||
|
||
T, η = is_meanfield ? (5_000, 1e-2) : (30_000, 1e-3) | ||
|
||
q0 = if is_meanfield | ||
MeanFieldGaussian(zeros(realtype, n_dims), Diagonal(ones(realtype, n_dims))) | ||
else | ||
L0 = Matrix{realtype}(I, n_dims, n_dims) |> LowerTriangular | ||
FullRankGaussian(zeros(realtype, n_dims), L0) | ||
end | ||
|
||
@testset "convergence" begin | ||
Δλ₀ = sum(abs2, q0.location - μ_true) + sum(abs2, q0.scale - L_true) | ||
q, stats, _ = optimize( | ||
rng, model, objective, q0, T; | ||
optimizer = Optimisers.Adam(realtype(η)), | ||
show_progress = PROGRESS, | ||
adbackend = adbackend, | ||
) | ||
|
||
μ = q.location | ||
L = q.scale | ||
Δλ = sum(abs2, μ - μ_true) + sum(abs2, L - L_true) | ||
|
||
@test Δλ ≤ Δλ₀/T^(1/4) | ||
@test eltype(μ) == eltype(μ_true) | ||
@test eltype(L) == eltype(L_true) | ||
end | ||
|
||
@testset "determinism" begin | ||
rng = StableRNG(seed) | ||
q, stats, _ = optimize( | ||
rng, model, objective, q0, T; | ||
optimizer = Optimisers.Adam(realtype(η)), | ||
show_progress = PROGRESS, | ||
adbackend = adbackend, | ||
) | ||
μ = q.location | ||
L = q.scale | ||
|
||
rng_repl = StableRNG(seed) | ||
q, stats, _ = optimize( | ||
rng_repl, model, objective, q0, T; | ||
optimizer = Optimisers.Adam(realtype(η)), | ||
show_progress = PROGRESS, | ||
adbackend = adbackend, | ||
) | ||
μ_repl = q.location | ||
L_repl = q.scale | ||
@test μ == μ_repl | ||
@test L == L_repl | ||
end | ||
end | ||
end | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.