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

Add Enzyme support #42

Merged
merged 1 commit into from
Feb 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/AdvancedVI.jl
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,34 @@ function __init__()
return out
end
end
@require Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9" begin
include("compat/enzyme.jl")
export EnzymeAD

function AdvancedVI.grad!(
vo,
alg::VariationalInference{<:AdvancedVI.EnzymeAD},
q,
model,
θ::AbstractVector{<:Real},
out::DiffResults.MutableDiffResult,
args...
)
f(θ) = if (q isa Distribution)
- vo(alg, update(q, θ), model, args...)
else
- vo(alg, q(θ), model, args...)
end
# Use `Enzyme.ReverseWithPrimal` once it is released:
# https://github.com/EnzymeAD/Enzyme.jl/pull/598
y = f(θ)
DiffResults.value!(out, y)
dy = DiffResults.gradient(out)
fill!(dy, 0)
Enzyme.autodiff(Enzyme.ReverseWithPrimal, f, Enzyme.Active, Enzyme.Duplicated(θ, dy))
return out
end
end
end

export
Expand Down
5 changes: 5 additions & 0 deletions src/compat/enzyme.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
struct EnzymeAD <: ADBackend end
ADBackend(::Val{:enzyme}) = EnzymeAD
function setadbackend(::Val{:enzyme})
ADBACKEND[] = :enzyme
end