-
Notifications
You must be signed in to change notification settings - Fork 82
feat: enzyme autodiff helpers #954
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
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1c57aaa
feat: add forward mode batched enzyme jacobian
avik-pal 5985015
feat: add reverse mode batched enzyme jacobian
avik-pal 0c1770e
feat: add vjp and jvp for Enzyme
avik-pal c15ccb2
fix: avoid closures in batched_jacobian
avik-pal d045b23
test: add batched jacobian tests for enzyme
avik-pal 3ed672d
feat: initial support for reactant
avik-pal 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,39 @@ | ||
| module LuxEnzymeExt | ||
|
|
||
| using ADTypes: AutoEnzyme | ||
| using Enzyme: Enzyme, Active, Const, Duplicated | ||
| using ADTypes: ADTypes, AutoEnzyme, ForwardMode, ReverseMode | ||
| using ArgCheck: @argcheck | ||
| using ConcreteStructs: @concrete | ||
| using Enzyme: Enzyme, Active, Const, Duplicated, BatchDuplicated | ||
| using EnzymeCore: EnzymeCore | ||
| using Functors: fmap | ||
| using Setfield: @set! | ||
| using Static: False, True | ||
| using Setfield: @set!, @set | ||
| using Static: False, True, StaticBool | ||
|
|
||
| using Lux: Lux, Utils | ||
| using Lux.Training: TrainingBackendCache, TrainState | ||
| using MLDataDevices: isleaf | ||
|
|
||
| Lux.is_extension_loaded(::Val{:Enzyme}) = true | ||
|
|
||
| normalize_backend(::StaticBool, ad::AutoEnzyme) = ad | ||
| normalize_backend(::True, ad::AutoEnzyme{Nothing}) = @set(ad.mode=Enzyme.Forward) | ||
| normalize_backend(::False, ad::AutoEnzyme{Nothing}) = @set(ad.mode=Enzyme.Reverse) | ||
|
|
||
| annotate_function(::AutoEnzyme{<:Any, Nothing}, f::F) where {F} = f | ||
| annotate_function(::AutoEnzyme{<:Any, A}, f::F) where {F, A} = A(f) | ||
|
|
||
| include("training.jl") | ||
|
|
||
| include("autodiff.jl") | ||
| include("batched_autodiff.jl") | ||
|
|
||
| @concrete struct OOPFunctionWrapper | ||
| f | ||
| end | ||
|
|
||
| function (f::OOPFunctionWrapper)(y, args...) | ||
| copyto!(y, f.f(args...)) | ||
| return | ||
| 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| function Lux.AutoDiffInternalImpl.jacobian_vector_product_impl( | ||
| f::F, ad::AutoEnzyme, x, u, p) where {F} | ||
| ad = normalize_backend(True(), ad) | ||
| @assert ADTypes.mode(ad) isa ForwardMode "JVPs are only supported in forward mode." | ||
| return only( | ||
| Enzyme.autodiff(ad.mode, annotate_function(ad, f), Duplicated(x, u), Const(p)) | ||
| ) | ||
| end | ||
|
|
||
| function Lux.AutoDiffInternalImpl.jacobian_vector_product_impl( | ||
| f::F, ad::AutoEnzyme, x, u) where {F} | ||
| ad = normalize_backend(True(), ad) | ||
| @assert ADTypes.mode(ad) isa ForwardMode "JVPs are only supported in forward mode." | ||
| return only(Enzyme.autodiff(ad.mode, annotate_function(ad, f), Duplicated(x, u))) | ||
| end | ||
|
|
||
| function Lux.AutoDiffInternalImpl.vector_jacobian_product_impl( | ||
| f::F, ad::AutoEnzyme, x, v, p) where {F} | ||
| ad = normalize_backend(False(), ad) | ||
| @assert ADTypes.mode(ad) isa ReverseMode "VJPs are only supported in reverse mode." | ||
| dx = zero(x) | ||
| # XXX: without the copy it overwrites the `v` with zeros | ||
| Enzyme.autodiff(ad.mode, annotate_function(ad, OOPFunctionWrapper(f)), | ||
| Duplicated(similar(v), copy(v)), Duplicated(x, dx), Const(p)) | ||
| return dx | ||
| end | ||
|
|
||
| function Lux.AutoDiffInternalImpl.vector_jacobian_product_impl( | ||
| f::F, ad::AutoEnzyme, x, v) where {F} | ||
| ad = normalize_backend(False(), ad) | ||
| @assert ADTypes.mode(ad) isa ReverseMode "VJPs are only supported in reverse mode." | ||
| dx = zero(x) | ||
| # XXX: without the copy it overwrites the `v` with zeros | ||
| Enzyme.autodiff(ad.mode, annotate_function(ad, OOPFunctionWrapper(f)), | ||
| Duplicated(similar(v), copy(v)), Duplicated(x, dx)) | ||
| return dx | ||
| 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,93 @@ | ||
| function Lux.AutoDiffInternalImpl.batched_jacobian_internal( | ||
| f::F, ad::AutoEnzyme, x::AbstractArray, args...) where {F} | ||
| backend = normalize_backend(True(), ad) | ||
| return batched_enzyme_jacobian_impl(f, backend, ADTypes.mode(backend), x, args...) | ||
| end | ||
|
|
||
| function batched_enzyme_jacobian_impl( | ||
| f_orig::G, ad::AutoEnzyme, ::ForwardMode, x::AbstractArray, args...) where {G} | ||
| # We need to run the function once to get the output type. Can we use ForwardWithPrimal? | ||
| y = f_orig(x) | ||
| f = annotate_function(ad, f_orig) | ||
|
|
||
| @argcheck y isa AbstractArray MethodError | ||
| if ndims(y) ≤ 1 || size(y, ndims(y)) != size(x, ndims(x)) | ||
| throw(AssertionError("`batched_jacobian` only supports batched outputs \ | ||
| (ndims(y) > 1) && size(y, ndims(y)) == size(x, ndims(x)).")) | ||
| end | ||
| B = size(y, ndims(y)) | ||
|
|
||
| J = similar(x, promote_type(eltype(y), eltype(x)), prod(size(y)[1:(end - 1)]), | ||
| prod(size(x)[1:(end - 1)]), B) | ||
|
|
||
| chunk_size = Utils.max_enzyme_batched_chunk_size(y) | ||
| partials = ntuple(_ -> zero(x), chunk_size) | ||
|
|
||
| for i in 1:chunk_size:(length(x) ÷ B) | ||
| idxs = i:min(i + chunk_size - 1, length(x) ÷ B) | ||
| partials′ = make_onehot!(partials, idxs) | ||
| J_partials = only(Enzyme.autodiff( | ||
| ad.mode, f, make_batch_duplicated(x, partials′), Const.(args)... | ||
| )) | ||
| for (idx, J_partial) in zip(idxs, J_partials) | ||
| J[:, :, idx] .= reshape(J_partial, :, B) | ||
| end | ||
| end | ||
|
|
||
| return J | ||
| end | ||
|
|
||
| function batched_enzyme_jacobian_impl( | ||
| f_orig::G, ad::AutoEnzyme, ::ReverseMode, x::AbstractArray, args...) where {G} | ||
| # We need to run the function once to get the output type. Can we use ReverseWithPrimal? | ||
| y = f_orig(x) | ||
|
|
||
| @argcheck y isa AbstractArray MethodError | ||
| if ndims(y) ≤ 1 || size(y, ndims(y)) != size(x, ndims(x)) | ||
| throw(AssertionError("`batched_jacobian` only supports batched outputs \ | ||
| (ndims(y) > 1) && size(y, ndims(y)) == size(x, ndims(x)).")) | ||
| end | ||
| B = size(y, ndims(y)) | ||
|
|
||
| J = similar(x, promote_type(eltype(y), eltype(x)), prod(size(y)[1:(end - 1)]), | ||
| prod(size(x)[1:(end - 1)]), B) | ||
|
|
||
| chunk_size = Utils.max_enzyme_batched_chunk_size(y) | ||
| partials = ntuple(_ -> zero(y), chunk_size) | ||
| J_partials = ntuple(_ -> zero(x), chunk_size) | ||
|
|
||
| fn = annotate_function(ad, OOPFunctionWrapper(f_orig)) | ||
| for i in 1:chunk_size:(length(y) ÷ B) | ||
| idxs = i:min(i + chunk_size - 1, length(y) ÷ B) | ||
| partials′ = make_onehot!(partials, idxs) | ||
| J_partials′ = make_zero!(J_partials, idxs) | ||
| Enzyme.autodiff( | ||
| ad.mode, fn, make_batch_duplicated(y, partials′), | ||
| make_batch_duplicated(x, J_partials′), Const.(args)... | ||
| ) | ||
| for (idx, J_partial) in zip(idxs, J_partials) | ||
| J[idx, :, :] .= reshape(J_partial, :, B) | ||
| end | ||
| end | ||
|
|
||
| return J | ||
| end | ||
|
|
||
| function make_onehot!(partials, idxs) | ||
| for (idx, partial) in zip(idxs, partials) | ||
| partial .= false | ||
| partial′ = reshape(partial, :, size(partial, ndims(partial))) | ||
| partial′[idx, :] .= true | ||
| end | ||
| return partials[1:length(idxs)] | ||
| end | ||
|
|
||
| function make_zero!(partials, idxs) | ||
| for partial in partials | ||
| partial .= false | ||
| end | ||
| return partials[1:length(idxs)] | ||
| end | ||
|
|
||
| make_batch_duplicated(x, dxs) = BatchDuplicated(x, dxs) | ||
| make_batch_duplicated(x, dx::Tuple{X}) where {X} = Duplicated(x, only(dx)) |
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
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
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
Oops, something went wrong.
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.