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

Fix Enzyme extension #38

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
8 changes: 3 additions & 5 deletions ext/NormalizingFlowsEnzymeExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,14 @@ else
using ..NormalizingFlows: ADTypes, DiffResults
end

# Enzyme doesn't support f::Bijectors (see https://github.com/EnzymeAD/Enzyme.jl/issues/916)
function NormalizingFlows.value_and_gradient!(
ad::ADTypes.AutoEnzyme, f, θ::AbstractVector{T}, out::DiffResults.MutableDiffResult
) where {T<:Real}
y = f(θ)
DiffResults.value!(out, y)
∇θ = DiffResults.gradient(out)
fill!(∇θ, zero(T))
Enzyme.autodiff(Enzyme.ReverseWithPrimal, f, Enzyme.Active, Enzyme.Duplicated(θ, ∇θ))
_, y = Enzyme.autodiff(Enzyme.ReverseWithPrimal, f, Enzyme.Active, Enzyme.Duplicated(θ, ∇θ))
DiffResults.value!(out, y)
return out
end

end
end
12 changes: 10 additions & 2 deletions test/ad.jl
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ end
ADTypes.AutoZygote(),
ADTypes.AutoForwardDiff(),
ADTypes.AutoReverseDiff(false),
# ADTypes.AutoEnzyme(), # not working now
ADTypes.AutoEnzyme(),
]
@testset "$T" for T in [Float32, Float64]
μ = 10 * ones(T, 2)
Expand All @@ -41,12 +41,20 @@ end
out = DiffResults.GradientResult(θ)

# check grad computation for elbo
# Enzyme needs a workaround
if at isa ADTypes.AutoEnzyme
activity = Enzyme.API.runtimeActivity()
Enzyme.API.runtimeActivity!(true)
end
NormalizingFlows.grad!(
Random.default_rng(), at, elbo, θ, re, out, logp, sample_per_iter
)
if at isa ADTypes.AutoEnzyme
Enzyme.API.runtimeActivity!(activity)
end

@test DiffResults.value(out) != nothing
@test all(DiffResults.gradient(out) .!= nothing)
end
end
end
end
Loading