diff --git a/ext/TensorOperationsChainRulesCoreExt.jl b/ext/TensorOperationsChainRulesCoreExt.jl index 02bdae1b..6596b8f9 100644 --- a/ext/TensorOperationsChainRulesCoreExt.jl +++ b/ext/TensorOperationsChainRulesCoreExt.jl @@ -17,10 +17,8 @@ using LinearAlgebra @non_differentiable TensorOperations.tensorstructure(args...) @non_differentiable TensorOperations.tensoradd_structure(args...) @non_differentiable TensorOperations.tensoradd_type(args...) -@non_differentiable TensorOperations.tensoralloc_add(args...) @non_differentiable TensorOperations.tensorcontract_structure(args...) @non_differentiable TensorOperations.tensorcontract_type(args...) -@non_differentiable TensorOperations.tensoralloc_contract(args...) @non_differentiable TensorOperations.promote_contract(args...) @non_differentiable TensorOperations.promote_add(args...) @non_differentiable TensorOperations.contract_indices(args...) @@ -36,13 +34,10 @@ function ChainRulesCore.rrule(::typeof(TensorOperations.tensorfree!), C, allocat return nothing, tensorfree!_pullback end function ChainRulesCore.rrule( - ::typeof(TensorOperations.tensoralloc), ttype, structure, - istemp, allocator = DefaultAllocator() + ::typeof(TensorOperations.tensoralloc), ttype, structure, istemp, args... ) - output = TensorOperations.tensoralloc(ttype, structure, Val(false), allocator) - function tensoralloc_pullback(Δargs...) - return (NoTangent(), NoTangent(), NoTangent(), NoTangent(), NoTangent()) - end + output = TensorOperations.tensoralloc(ttype, structure, Val(false), args...) + tensoralloc_pullback(Δ) = ntuple(Returns(NoTangent()), 4 + length(args)) return output, tensoralloc_pullback end diff --git a/ext/TensorOperationsEnzymeExt/TensorOperationsEnzymeExt.jl b/ext/TensorOperationsEnzymeExt/TensorOperationsEnzymeExt.jl index 97c92ed6..32aecdb4 100644 --- a/ext/TensorOperationsEnzymeExt/TensorOperationsEnzymeExt.jl +++ b/ext/TensorOperationsEnzymeExt/TensorOperationsEnzymeExt.jl @@ -2,14 +2,13 @@ module TensorOperationsEnzymeExt using TensorOperations using TensorOperations: AbstractBackend, DefaultAllocator, CUDAAllocator, ManualAllocator +using TensorOperations.PtrArrays: PtrArray using VectorInterface using TupleTools using Enzyme using Enzyme.EnzymeCore using Enzyme.EnzymeCore: EnzymeRules -@inline EnzymeRules.inactive(::typeof(TensorOperations.tensorfree!), ::Any) = true -@inline EnzymeRules.inactive(::typeof(TensorOperations.tensorfree!), ::Any, ::Any) = true @inline EnzymeRules.inactive_type(v::Type{<:AbstractBackend}) = true @inline EnzymeRules.inactive_type(v::Type{DefaultAllocator}) = true @inline EnzymeRules.inactive_type(v::Type{<:CUDAAllocator}) = true @@ -38,11 +37,11 @@ function EnzymeRules.augmented_primal( ::Type{RT}, ttype::Const, structure::Const, - istemp::Const{Bool}, + istemp::Const, allocator::Const ) where {RT} primal = EnzymeRules.needs_primal(config) ? TensorOperations.tensoralloc(ttype.val, structure.val, Val(false), allocator.val) : nothing - shadow = EnzymeRules.needs_shadow(config) ? TensorOperations.tensoralloc(ttype.val, structure.val, Val(false), allocator.val) : nothing + shadow = EnzymeRules.needs_shadow(config) ? zerovector!(TensorOperations.tensoralloc(ttype.val, structure.val, Val(false), allocator.val)) : nothing return EnzymeRules.AugmentedReturn(primal, shadow, nothing) end @@ -53,12 +52,64 @@ function EnzymeRules.reverse( cache, ttype::Const, structure::Const, - istemp::Const{Bool}, + istemp::Const, allocator::Const, ) where {RT} return nothing, nothing, nothing, nothing end +function EnzymeRules.augmented_primal( + config::EnzymeRules.RevConfigWidth{1}, + func::Const{typeof(TensorOperations.tensoralloc)}, + ::Type{RT}, + ttype::Const, + structure::Const, + istemp::Const{Val{true}}, + allocator::Const{ManualAllocator} + ) where {RT} + primal_data = TensorOperations.tensoralloc(ttype.val, structure.val, Val(false), allocator.val) + primal = PtrArray(pointer(primal_data), size(primal_data)...) + if EnzymeRules.needs_shadow(config) + shadow_data = zerovector!(TensorOperations.tensoralloc(ttype.val, structure.val, Val(false), allocator.val)) + shadow = PtrArray(pointer(shadow_data), size(shadow_data)...) + else + shadow, shadow_data = nothing, nothing + end + return EnzymeRules.AugmentedReturn( + EnzymeRules.needs_primal(config) ? primal : nothing, shadow, (primal_data, shadow_data) + ) +end +function EnzymeRules.reverse( + config::EnzymeRules.RevConfigWidth{1}, + func::Const{typeof(TensorOperations.tensoralloc)}, + ::Type{RT}, + cache, + ttype::Const, + structure::Const, + istemp::Const{Val{true}}, + allocator::Const{ManualAllocator}, + ) where {RT} + return nothing, nothing, nothing, nothing +end + +function EnzymeRules.augmented_primal( + config::EnzymeRules.RevConfigWidth{1}, + func::Const{typeof(TensorOperations.tensorfree!)}, + ::Type{RT}, + args::Annotation... + ) where {RT} + return EnzymeRules.AugmentedReturn(nothing, nothing, nothing) +end +function EnzymeRules.reverse( + config::EnzymeRules.RevConfigWidth{1}, + func::Const{typeof(TensorOperations.tensorfree!)}, + ::Type{RT}, + cache, + args::Annotation... + ) where {RT} + return ntuple(Returns(nothing), length(args)) +end + function EnzymeRules.augmented_primal( config::EnzymeRules.RevConfigWidth{1}, func::Const{typeof(TensorOperations.tensorcontract!)}, diff --git a/ext/TensorOperationsMooncakeExt/TensorOperationsMooncakeExt.jl b/ext/TensorOperationsMooncakeExt/TensorOperationsMooncakeExt.jl index 2ea5db53..c1ae27fc 100644 --- a/ext/TensorOperationsMooncakeExt/TensorOperationsMooncakeExt.jl +++ b/ext/TensorOperationsMooncakeExt/TensorOperationsMooncakeExt.jl @@ -9,6 +9,7 @@ using TensorOperations: AbstractBackend, DefaultAllocator, CUDAAllocator, Manual using TensorOperations: tensoralloc, tensoradd!, tensorcontract!, tensortrace! using Mooncake: ReverseMode, DefaultCtx, Dual, CoDual, NoRData, arrayify, @zero_derivative, primal, tangent using VectorInterface, TupleTools +using TensorOperations.PtrArrays: PtrArray Mooncake.tangent_type(::Type{Index2Tuple}) = Mooncake.NoTangent Mooncake.tangent_type(::Type{<:AbstractBackend}) = Mooncake.NoTangent @@ -29,6 +30,30 @@ Mooncake.tangent_type(::Type{ManualAllocator}) = Mooncake.NoTangent Mooncake.@from_rrule Mooncake.DefaultCtx Tuple{typeof(TensorOperations.tensorfree!), Any} Mooncake.@from_rrule Mooncake.DefaultCtx Tuple{typeof(TensorOperations.tensorfree!), Any, Any} Mooncake.@from_rrule Mooncake.DefaultCtx Tuple{typeof(TensorOperations.tensoralloc), Any, Any, Any, Any} +Mooncake.@from_rrule Mooncake.DefaultCtx Tuple{typeof(TensorOperations.tensoralloc), Any, Any, Any, Any, Any} + +Mooncake.@is_primitive DefaultCtx Tuple{typeof(tensoralloc), Type{<:AbstractArray}, Any, Val{true}, ManualAllocator} +function Mooncake.rrule!!( + ::CoDual{typeof(tensoralloc)}, ttype_dttype::CoDual{<:Type{<:AbstractArray}}, structure_dstructure::CoDual, + istemp_distemp::CoDual{Val{true}}, allocator_dallocator::CoDual{ManualAllocator} + ) + ttype, structure, allocator = primal(ttype_dttype), primal(structure_dstructure), primal(allocator_dallocator) + C_data = tensoralloc(ttype, structure, Val(false), allocator) + C = PtrArray(pointer(C_data), size(C_data)...) + dC_data = zerovector!(tensoralloc(ttype, structure, Val(false), allocator)) + dC = PtrArray(pointer(dC_data), size(dC_data)...) + function tensoralloc_pullback(::NoRData) + GC.@preserve C_data dC_data nothing + return ntuple(Returns(NoRData()), 5) + end + return CoDual(C, _fdata(C, dC)), tensoralloc_pullback +end +_fdata(::PtrArray{T}, dC::PtrArray{T}) where {T} = + Mooncake.FData((; ptr = Ptr{Mooncake.tangent_type(T)}(dC.ptr), size = Mooncake.NoFData())) + +# `Mooncake.arrayify` does not know about the `PtrArray`s of a `ManualAllocator` +_arrayify(x::CoDual{<:PtrArray}) = primal(x), PtrArray(tangent(x).data.ptr, size(primal(x))...) +_arrayify(x) = arrayify(x) Mooncake.@is_primitive DefaultCtx Tuple{typeof(tensorcontract!), AbstractArray, AbstractArray, Index2Tuple, Bool, AbstractArray, Index2Tuple, Bool, Index2Tuple, Number, Number, Vararg{Any}} function Mooncake.rrule!!( @@ -45,9 +70,9 @@ function Mooncake.rrule!!( β_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) + 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) @@ -82,9 +107,9 @@ function Mooncake.frule!!( β_dβ::Dual{Tβ}, ba_dba::Dual..., ) 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) + 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) @@ -119,8 +144,8 @@ function Mooncake.rrule!!( β_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) + C, dC = _arrayify(C_dC) + A, dA = _arrayify(A_dA) pA = primal(pA_dpA) conjA = primal(conjA_dconjA) α = primal(α_dα) @@ -148,8 +173,8 @@ function Mooncake.frule!!( β_dβ::Dual{Tβ}, ba_dba::Dual..., ) where {Tα <: Number, Tβ <: Number, TA <: Number, TC <: Number} - C, dC = arrayify(C_dC) - A, dA = arrayify(A_dA) + C, dC = _arrayify(C_dC) + A, dA = _arrayify(A_dA) pA = primal(pA_dpA) conjA = primal(conjA_dconjA) α = primal(α_dα) @@ -186,8 +211,8 @@ function Mooncake.rrule!!( β_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) + C, dC = _arrayify(C_dC) + A, dA = _arrayify(A_dA) p = primal(p_dp) q = primal(q_dq) conjA = primal(conjA_dconjA) @@ -217,8 +242,8 @@ function Mooncake.frule!!( β_dβ::Dual{Tβ}, ba_dba::Dual..., ) where {Tα <: Number, Tβ <: Number, TA <: Number, TC <: Number} - C, dC = arrayify(C_dC) - A, dA = arrayify(A_dA) + C, dC = _arrayify(C_dC) + A, dA = _arrayify(A_dA) p = primal(p_dp) q = primal(q_dq) conjA = primal(conjA_dconjA) diff --git a/test/ad.jl b/test/ad.jl index 1be00fc8..992d6915 100644 --- a/test/ad.jl +++ b/test/ad.jl @@ -2,7 +2,7 @@ using TensorOperations using TensorOperations: StridedBLAS, StridedNative using Test using ChainRulesTestUtils -using ChainRulesCore: NoTangent +using ChainRulesCore: ChainRulesCore, NoTangent using VectorInterface: Zero ChainRulesTestUtils.test_method_tables() diff --git a/test/enzyme.jl b/test/enzyme.jl index 1f6064c6..42c812af 100644 --- a/test/enzyme.jl +++ b/test/enzyme.jl @@ -285,3 +285,27 @@ end @test all(RUNTIME_ACTIVITY_OPS[k] == ops[k] for k in keys(ops)) @test dx ≈ sum(vec(sum(op; dims = 1)) .+ 2 * sum(x) .+ [1, 0, 0, 0] for op in values(ops)) end + +# the intermediate `A * B` of the first block is needed in the reverse pass after the second block +# has reused (`BufferAllocator`) or the first block has freed (`ManualAllocator`) its storage +function enzyme_two_tensor_blocks(A, B, D, allocator) + @tensor allocator = allocator C[a, b] := A[a, c] * B[c, d] * D[d, b] + @tensor allocator = allocator E[a, b] := D[a, c] * B[c, d] * C[d, b] + return sum(abs2, E) +end + +@testset "temporaries of $(nameof(typeof(allocator)))" for allocator in + (TensorOperations.ManualAllocator(), TensorOperations.BufferAllocator()) + A, B, D = randn(4, 4), randn(4, 4), randn(4, 4) + function gradient(allocator) + dA, dB, dD = zero(A), zero(B), zero(D) + Enzyme.autodiff( + Reverse, enzyme_two_tensor_blocks, Active, + Duplicated(A, dA), Duplicated(B, dB), Duplicated(D, dD), Const(allocator) + ) + return dA, dB, dD + end + ref = gradient(TensorOperations.DefaultAllocator()) + @test all(gradient(allocator) .≈ ref) + @test all(gradient(allocator) .≈ ref) +end diff --git a/test/mooncake.jl b/test/mooncake.jl index 342867f0..6d6a3238 100644 --- a/test/mooncake.jl +++ b/test/mooncake.jl @@ -1,5 +1,5 @@ using TensorOperations -using TensorOperations: StridedBLAS, StridedNative, tensortrace!, Zero +using TensorOperations: StridedBLAS, StridedNative, tensortrace!, tensoralloc, Zero using Test using Mooncake using Random @@ -102,3 +102,38 @@ end fill!(C, rand(T)) Mooncake.TestUtils.test_rule(rng, tensorscalar, C; atol, rtol, is_primitive) end + +# the intermediate `A * B` of the first block is needed in the pullback after the second block +# has reused (`BufferAllocator`) or the first block has freed (`ManualAllocator`) its storage +function mooncake_two_tensor_blocks(A, B, D, allocator) + @tensor allocator = allocator C[a, b] := A[a, c] * B[c, d] * D[d, b] + @tensor allocator = allocator E[a, b] := D[a, c] * B[c, d] * C[d, b] + return sum(abs2, E) +end + +@testset "temporaries of $(nameof(typeof(allocator)))" for allocator in + (TensorOperations.ManualAllocator(), TensorOperations.BufferAllocator()) + A, B, D = randn(rng, 4, 4), randn(rng, 4, 4), randn(rng, 4, 4) + function gradient(allocator) + f = (A, B, D) -> mooncake_two_tensor_blocks(A, B, D, allocator) + cache = Mooncake.prepare_gradient_cache(f, A, B, D) + val, (_, dA, dB, dD) = Mooncake.value_and_gradient!!(cache, f, A, B, D) + return val, copy(dA), copy(dB), copy(dD) + end + ref = gradient(TensorOperations.DefaultAllocator()) + res = gradient(allocator) + @test all(res .≈ ref) + # repeated calls reuse the prepared rules without leaking or reusing freed temporaries + @test all(gradient(allocator) .≈ ref) +end + +@testset "No double free for ManualAllocator" begin + allocator = TensorOperations.ManualAllocator() + C_dC, pb = Mooncake.rrule!!( + Mooncake.zero_fcodual(tensoralloc), Mooncake.zero_fcodual(Matrix{Float64}), + Mooncake.zero_fcodual((16, 16)), Mooncake.zero_fcodual(Val(true)), Mooncake.zero_fcodual(allocator) + ) + @test Mooncake.primal(C_dC) isa TensorOperations.PtrArrays.PtrArray{Float64, 2} + @test pb(Mooncake.NoRData()) == ntuple(Returns(Mooncake.NoRData()), 5) + @test pb(Mooncake.NoRData()) == ntuple(Returns(Mooncake.NoRData()), 5) +end