-
Notifications
You must be signed in to change notification settings - Fork 68
Rules with Mooncake #240
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
Merged
Rules with Mooncake #240
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
eafefca
Rules with Mooncake
kshyatt 3db9779
Bump version and minimum Julia requirement
kshyatt d6a1481
No custom rule for tensorscalar
kshyatt 4e096f8
Use scale to make things more generic
kshyatt dca7fcc
Fix bad dC behaviour
kshyatt 827815c
More consistency
kshyatt d4a366b
Just use beta to scale
kshyatt 402b36a
See you later allocator
kshyatt 39b35d8
Vararg
kshyatt 71f7b4b
Format
kshyatt d75b8ed
Comments
573bf47
Update autodiff.md with warnings
kshyatt a782005
Fix typo
kshyatt 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
Some comments aren't visible on the classic Files Changed page.
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 |
|---|---|---|
| @@ -1,25 +1,32 @@ | ||
| # Automatic differentiation | ||
|
|
||
| TensorOperations offers experimental support for reverse-mode automatic diffentiation (AD) | ||
| through the use of [ChainRules.jl](https://github.com/JuliaDiff/ChainRules.jl). As the basic | ||
| through the use of [ChainRules.jl](https://github.com/JuliaDiff/ChainRules.jl) | ||
| and [Mooncake.jl](https://github.com/chalk-lab/Mooncake.jl). As the basic | ||
| operations are multi-linear, the vector-Jacobian products thereof can all be expressed in | ||
| terms of the operations defined in VectorInterface and TensorOperations. Thus, any custom | ||
| type whose tangent type also support these interfaces will automatically inherit | ||
| reverse-mode AD support. | ||
|
|
||
| As the [`@tensor`](@ref) macro rewrites everything in terms of the basic tensor operations, | ||
| the reverse-mode rules for these methods are supplied. However, because most AD-engines do | ||
| the reverse-mode rules for these methods are supplied. However, because ChainRules.jl does | ||
| not support in-place mutation, effectively these operations will be replaced with a | ||
| non-mutating version. This is similar to the behaviour found in | ||
| [BangBang.jl](https://github.com/JuliaFolds/BangBang.jl), as the operations will be | ||
| in-place, except for the pieces of code that are being differentiated. In effect, this | ||
| amounts to replacing all assignments (`=`) with definitions (`:=`) within the context of | ||
| [`@tensor`](@ref). | ||
|
|
||
| Mooncake.jl *does* support in-place mutation, and as a result on the reverse pass | ||
| all mutated input variables should be restored to their state before the forward-pass | ||
| function was called. Currently, this is **not done** for buffers you provide to various | ||
| TensorOperations functions, so relying on the state of the buffer (e.g. a bumper) being | ||
| restored will **silently** return incorrect results. | ||
|
|
||
| !!! warning "Experimental" | ||
|
|
||
| While some rudimentary tests are run, the AD support is currently not incredibly | ||
| well-tested. Because of the way it is implemented, the use of AD will tacitly replace | ||
| mutating operations with a non-mutating variant. This might lead to unwanted bugs that | ||
| are hard to track down. Additionally, for mixed scalar types their also might be | ||
| unexpected or unwanted behaviour. | ||
| are hard to track down. Additionally, for mixed scalar types there also might be | ||
| unexpected or unwanted behaviour. |
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
265 changes: 265 additions & 0 deletions
265
ext/TensorOperationsMooncakeExt/TensorOperationsMooncakeExt.jl
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,265 @@ | ||
| module TensorOperationsMooncakeExt | ||
|
|
||
| using TensorOperations | ||
| # Mooncake imports ChainRulesCore as CRC to avoid name conflicts | ||
| # here we import it ourselves to ensure the rules from the ChainRulesCore | ||
| # extension are in fact loaded | ||
| using Mooncake, Mooncake.CRC | ||
| using TensorOperations: AbstractBackend, DefaultAllocator, CUDAAllocator, ManualAllocator | ||
| using TensorOperations: tensoralloc, tensoradd!, tensorcontract!, tensortrace!, _kron, numind, _needs_tangent, numin, numout | ||
| using Mooncake: ReverseMode, DefaultCtx, CoDual, NoRData, arrayify, @zero_derivative, primal, tangent | ||
| using VectorInterface, TupleTools | ||
|
|
||
| Mooncake.tangent_type(::Type{Index2Tuple}) = Mooncake.NoTangent | ||
| Mooncake.tangent_type(::Type{<:AbstractBackend}) = Mooncake.NoTangent | ||
| Mooncake.tangent_type(::Type{DefaultAllocator}) = Mooncake.NoTangent | ||
| Mooncake.tangent_type(::Type{CUDAAllocator}) = Mooncake.NoTangent | ||
| Mooncake.tangent_type(::Type{ManualAllocator}) = Mooncake.NoTangent | ||
|
|
||
| trivtuple(N) = ntuple(identity, N) | ||
|
|
||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.tensorstructure), Any} | ||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.tensoradd_structure), Any} | ||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.tensoradd_type), Any} | ||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.tensoralloc_add), Any} | ||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.tensorcontract_structure), Any} | ||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.tensorcontract_type), Any} | ||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.tensoralloc_contract), Any} | ||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.promote_contract), Any} | ||
| @zero_derivative DefaultCtx Tuple{typeof(TensorOperations.promote_add), Any} | ||
|
|
||
| Mooncake.@from_rrule Mooncake.DefaultCtx Tuple{typeof(TensorOperations.tensorfree!), Any} | ||
| Mooncake.@from_rrule Mooncake.DefaultCtx Tuple{typeof(TensorOperations.tensoralloc), Any, Any, Any, Any} | ||
|
|
||
| Mooncake.@is_primitive DefaultCtx ReverseMode Tuple{typeof(tensorcontract!), AbstractArray, AbstractArray, Index2Tuple, Bool, AbstractArray, Index2Tuple, Bool, Index2Tuple, Number, Number, Vararg{Any}} | ||
| function Mooncake.rrule!!( | ||
| ::CoDual{typeof(tensorcontract!)}, | ||
| C_dC::CoDual{<:AbstractArray{TC}}, | ||
| A_dA::CoDual{<:AbstractArray{TA}}, | ||
| pA_dpA::CoDual{<:Index2Tuple}, | ||
| conjA_dconjA::CoDual{Bool}, | ||
| B_dB::CoDual{<:AbstractArray{TB}}, | ||
| pB_dpB::CoDual{<:Index2Tuple}, | ||
| conjB_dconjB::CoDual{Bool}, | ||
| pAB_dpAB::CoDual{<:Index2Tuple}, | ||
| α_dα::CoDual{Tα}, | ||
| β_dβ::CoDual{Tβ}, | ||
| ba_dba::CoDual..., | ||
| ) where {Tα <: Number, Tβ <: Number, TA <: Number, TB <: Number, TC <: Number} | ||
| C, dC = arrayify(C_dC) | ||
| A, dA = arrayify(A_dA) | ||
| B, dB = arrayify(B_dB) | ||
| pA = primal(pA_dpA) | ||
| pB = primal(pB_dpB) | ||
| pAB = primal(pAB_dpAB) | ||
| conjA = primal(conjA_dconjA) | ||
| conjB = primal(conjB_dconjB) | ||
| α = primal(α_dα) | ||
| β = primal(β_dβ) | ||
| ba = primal.(ba_dba) | ||
| C_cache = copy(C) | ||
| TensorOperations.tensorcontract!(C, A, pA, conjA, B, pB, conjB, pAB, α, β, ba...) | ||
| function contract_pb(::NoRData) | ||
| scale!(C, C_cache, One()) | ||
| if Tα == Zero && Tβ == Zero | ||
| scale!(dC, zero(TC)) | ||
| return ntuple(i -> NoRData(), 11 + length(ba)) | ||
| end | ||
| ipAB = invperm(linearize(pAB)) | ||
| pdC = ( | ||
| TupleTools.getindices(ipAB, trivtuple(numout(pA))), | ||
| TupleTools.getindices(ipAB, numout(pA) .+ trivtuple(numin(pB))), | ||
| ) | ||
| ipA = (invperm(linearize(pA)), ()) | ||
| ipB = (invperm(linearize(pB)), ()) | ||
| conjΔC = conjA | ||
| conjB′ = conjA ? conjB : !conjB | ||
| dA = tensorcontract!( | ||
| dA, | ||
| dC, pdC, conjΔC, | ||
| B, reverse(pB), conjB′, | ||
| ipA, | ||
| conjA ? α : conj(α), One(), ba... | ||
| ) | ||
| conjΔC = conjB | ||
| conjA′ = conjB ? conjA : !conjA | ||
| dB = tensorcontract!( | ||
| dB, | ||
| A, reverse(pA), conjA′, | ||
| dC, pdC, conjΔC, | ||
| ipB, | ||
| conjB ? α : conj(α), One(), ba... | ||
| ) | ||
| dα = if _needs_tangent(Tα) | ||
| C_αβ = tensorcontract(A, pA, conjA, B, pB, conjB, pAB, One(), ba...) | ||
| # TODO: consider using `inner` | ||
| Mooncake._rdata( | ||
| tensorscalar( | ||
| tensorcontract( | ||
| C_αβ, ((), trivtuple(numind(pAB))), true, | ||
| dC, (trivtuple(numind(pAB)), ()), false, | ||
| ((), ()), One(), ba... | ||
| ) | ||
| ) | ||
| ) | ||
| else | ||
| NoRData() | ||
| end | ||
| dβ = if _needs_tangent(Tβ) | ||
| # TODO: consider using `inner` | ||
| Mooncake._rdata( | ||
| tensorscalar( | ||
| tensorcontract( | ||
| C, ((), trivtuple(numind(pAB))), true, | ||
| dC, (trivtuple(numind(pAB)), ()), false, | ||
| ((), ()), One(), ba... | ||
| ) | ||
| ) | ||
| ) | ||
| else | ||
| NoRData() | ||
| end | ||
| if β === Zero() | ||
| scale!(dC, β) | ||
| else | ||
| scale!(dC, conj(β)) | ||
| end | ||
| return NoRData(), NoRData(), NoRData(), NoRData(), NoRData(), NoRData(), NoRData(), NoRData(), NoRData(), dα, dβ, map(ba_ -> NoRData(), ba)... | ||
| end | ||
| return C_dC, contract_pb | ||
| end | ||
|
|
||
| Mooncake.@is_primitive DefaultCtx ReverseMode Tuple{typeof(tensoradd!), AbstractArray, AbstractArray, Index2Tuple, Bool, Number, Number, Vararg{Any}} | ||
| function Mooncake.rrule!!( | ||
| ::CoDual{typeof(tensoradd!)}, | ||
| C_dC::CoDual{<:AbstractArray{TC}}, | ||
| A_dA::CoDual{<:AbstractArray{TA}}, | ||
| pA_dpA::CoDual{<:Index2Tuple}, | ||
| conjA_dconjA::CoDual{Bool}, | ||
| α_dα::CoDual{Tα}, | ||
| β_dβ::CoDual{Tβ}, | ||
| ba_dba::CoDual..., | ||
| ) where {Tα <: Number, Tβ <: Number, TA <: Number, TC <: Number} | ||
| C, dC = arrayify(C_dC) | ||
| A, dA = arrayify(A_dA) | ||
| pA = primal(pA_dpA) | ||
| conjA = primal(conjA_dconjA) | ||
| α = primal(α_dα) | ||
| β = primal(β_dβ) | ||
| ba = primal.(ba_dba) | ||
| C_cache = copy(C) | ||
| TensorOperations.tensoradd!(C, A, pA, conjA, α, β, ba...) | ||
| function add_pb(::NoRData) | ||
| scale!(C, C_cache, One()) | ||
| ipA = invperm(linearize(pA)) | ||
| dA = tensoradd!(dA, dC, (ipA, ()), conjA, conjA ? α : conj(α), One(), ba...) | ||
| dα = if _needs_tangent(Tα) | ||
| tensorscalar( | ||
| tensorcontract( | ||
| A, ((), linearize(pA)), !conjA, | ||
| dC, (trivtuple(numind(pA)), ()), false, | ||
| ((), ()), One(), ba... | ||
| ) | ||
| ) | ||
| else | ||
| Mooncake.NoRData() | ||
| end | ||
| dβ = if _needs_tangent(Tβ) | ||
| tensorscalar( | ||
| tensorcontract( | ||
| C, ((), trivtuple(numind(pA))), true, | ||
| dC, (trivtuple(numind(pA)), ()), false, | ||
| ((), ()), One(), ba... | ||
| ) | ||
| ) | ||
| else | ||
| Mooncake.NoRData() | ||
| end | ||
| if β === Zero() | ||
| scale!(dC, β) | ||
| else | ||
| scale!(dC, conj(β)) | ||
| end | ||
| return NoRData(), NoRData(), NoRData(), NoRData(), NoRData(), dα, dβ, map(ba_ -> NoRData(), ba)... | ||
| end | ||
| return C_dC, add_pb | ||
| end | ||
|
|
||
| Mooncake.@is_primitive DefaultCtx ReverseMode Tuple{typeof(tensortrace!), AbstractArray, AbstractArray, Index2Tuple, Index2Tuple, Bool, Number, Number, Vararg{Any}} | ||
| function Mooncake.rrule!!( | ||
| ::CoDual{typeof(tensortrace!)}, | ||
| C_dC::CoDual{<:AbstractArray{TC}}, | ||
| A_dA::CoDual{<:AbstractArray{TA}}, | ||
| p_dp::CoDual{<:Index2Tuple}, | ||
| q_dq::CoDual{<:Index2Tuple}, | ||
| conjA_dconjA::CoDual{Bool}, | ||
| α_dα::CoDual{Tα}, | ||
| β_dβ::CoDual{Tβ}, | ||
| ba_dba::CoDual..., | ||
| ) where {Tα <: Number, Tβ <: Number, TA <: Number, TC <: Number} | ||
| C, dC = arrayify(C_dC) | ||
| A, dA = arrayify(A_dA) | ||
| p = primal(p_dp) | ||
| q = primal(q_dq) | ||
| conjA = primal(conjA_dconjA) | ||
| α = primal(α_dα) | ||
| β = primal(β_dβ) | ||
| ba = primal.(ba_dba) | ||
| C_cache = copy(C) | ||
| TensorOperations.tensortrace!(C, A, p, q, conjA, α, β, ba...) | ||
| function trace_pb(::NoRData) | ||
| scale!(C, C_cache, One()) | ||
| ip = invperm((linearize(p)..., q[1]..., q[2]...)) | ||
| Es = map(q[1], q[2]) do i1, i2 | ||
| one( | ||
| TensorOperations.tensoralloc_add( | ||
| TensorOperations.scalartype(A), A, ((i1,), (i2,)), conjA | ||
| ) | ||
| ) | ||
| end | ||
| E = _kron(Es, ba) | ||
| dA = tensorproduct!( | ||
| dA, dC, (trivtuple(numind(p)), ()), conjA, | ||
| E, ((), trivtuple(numind(q))), conjA, | ||
| (ip, ()), | ||
| conjA ? α : conj(α), One(), ba... | ||
| ) | ||
| C_αβ = tensortrace(A, p, q, false, One(), ba...) | ||
| dα = if _needs_tangent(Tα) | ||
| Mooncake._rdata( | ||
| tensorscalar( | ||
| tensorcontract( | ||
| C_αβ, ((), trivtuple(numind(p))), | ||
| !conjA, | ||
| dC, (trivtuple(numind(p)), ()), false, | ||
| ((), ()), One(), ba... | ||
| ) | ||
| ) | ||
| ) | ||
| else | ||
| NoRData() | ||
| end | ||
| dβ = if _needs_tangent(Tβ) | ||
| Mooncake._rdata( | ||
| tensorscalar( | ||
| tensorcontract( | ||
| C, ((), trivtuple(numind(p))), true, | ||
| dC, (trivtuple(numind(p)), ()), false, | ||
| ((), ()), One(), ba... | ||
| ) | ||
| ) | ||
| ) | ||
| else | ||
| NoRData() | ||
| end | ||
| if β === Zero() | ||
| scale!(dC, β) | ||
| else | ||
| scale!(dC, conj(β)) | ||
| end | ||
| return NoRData(), NoRData(), NoRData(), NoRData(), NoRData(), NoRData(), dα, dβ, map(ba_ -> NoRData(), ba)... | ||
| end | ||
| return C_dC, trace_pb | ||
| 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.
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.