Skip to content

Commit 0988e79

Browse files
kshyattKatharine Hyatt
andauthored
Enzyme reverse mode rules and test for index manipulations (#466)
* Enzyme reverse rules for index manipulation * Combine some pullbacks * Cleanup and soothe permute * Consolidate tests * No deepcopy should be needed * Remove unnecessary copies --------- Co-authored-by: Katharine Hyatt <katharine.s.hyatt@gmail.com>
1 parent 535a3c7 commit 0988e79

13 files changed

Lines changed: 489 additions & 24 deletions

File tree

‎ext/TensorKitEnzymeExt/TensorKitEnzymeExt.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ using Random: AbstractRNG
1212

1313
include("utility.jl")
1414
include("linalg.jl")
15+
include("indexmanipulations.jl")
1516

1617
end
Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
for transform in (:permute, :transpose)
2+
transform! = Symbol(transform, :!)
3+
transform_pb = Symbol(transform, :_pullback_dA)
4+
@eval function EnzymeRules.augmented_primal(
5+
config::EnzymeRules.RevConfigWidth{1},
6+
func::Const{typeof(TK.$transform!)},
7+
::Type{RT},
8+
C::Annotation{<:AbstractTensorMap},
9+
A::Annotation{<:AbstractTensorMap},
10+
p::Const{<:Index2Tuple},
11+
α::Annotation{<:Number},
12+
β::Annotation{<:Number},
13+
ba::Const...
14+
) where {RT}
15+
C_cache = !isa(β, Const) ? copy(C.val) : nothing
16+
A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
17+
# if we need to compute Δa, it is faster to allocate an intermediate permuted A
18+
# and store that instead of repeating the permutation in the pullback each time.
19+
# effectively, we replace `add_permute` by `add ∘ permute`.
20+
Ap = if !isa(α, Const)
21+
Ap = $transform(A.val, p.val)
22+
add!(C.val, Ap, α.val, β.val)
23+
Ap
24+
else
25+
bavs = map(a -> a.val, ba)
26+
TK.$transform!(C.val, A.val, p.val, α.val, β.val, bavs...)
27+
nothing
28+
end
29+
cache = (C_cache, A_cache, Ap)
30+
primal = EnzymeRules.needs_primal(config) ? C.val : nothing
31+
shadow = EnzymeRules.needs_shadow(config) ? C.dval : nothing
32+
return EnzymeRules.AugmentedReturn(primal, shadow, cache)
33+
end
34+
@eval function EnzymeRules.reverse(
35+
config::EnzymeRules.RevConfigWidth{1},
36+
func::Const{typeof(TK.$transform!)},
37+
::Type{RT},
38+
cache,
39+
C::Annotation{<:AbstractTensorMap},
40+
A::Annotation{<:AbstractTensorMap},
41+
p::Const{<:Index2Tuple},
42+
α::Annotation{<:Number},
43+
β::Annotation{<:Number},
44+
ba::Const...
45+
) where {RT}
46+
C_cache, A_cache, Ap = cache
47+
Cval = something(C_cache, C.val)
48+
bavs = map(a -> a.val, ba)
49+
# ΔA
50+
if !isa(A, Const) && !isa(C, Const)
51+
Aval = something(A_cache, A.val)
52+
TK.$transform_pb(A.dval, Aval, C.dval, C.val, p.val, α.val, bavs...)
53+
end
54+
Δα = pullback_dα(α, C, Ap)
55+
Δβ = pullback_dβ(β, C, Cval)
56+
!isa(C, Const) && pullback_dC!(C.dval, β.val)
57+
return nothing, nothing, nothing, Δα, Δβ, map(Returns(nothing), ba)...
58+
end
59+
end
60+
61+
function EnzymeRules.augmented_primal(
62+
config::EnzymeRules.RevConfigWidth{1},
63+
func::Const{typeof(TK.braid!)},
64+
::Type{RT},
65+
C::Annotation{<:AbstractTensorMap},
66+
A::Annotation{<:AbstractTensorMap},
67+
p::Const{<:Index2Tuple},
68+
levels::Const{<:IndexTuple},
69+
α::Annotation{<:Number},
70+
β::Annotation{<:Number},
71+
ba::Const...
72+
) where {RT}
73+
C_cache = !isa(β, Const) ? copy(C.val) : nothing
74+
A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
75+
# if we need to compute Δa, it is faster to allocate an intermediate braided A
76+
# and store that instead of repeating the permutation in the pullback each time.
77+
# effectively, we replace `add_permute` by `add ∘ permute`.
78+
Ap = if !isa(α, Const)
79+
Ap = braid(A.val, p.val, levels.val)
80+
add!(C.val, Ap, α.val, β.val)
81+
Ap
82+
else
83+
bavs = map(a -> a.val, ba)
84+
TK.braid!(C.val, A.val, p.val, levels.val, α.val, β.val, bavs...)
85+
nothing
86+
end
87+
cache = (C_cache, A_cache, Ap)
88+
primal = EnzymeRules.needs_primal(config) ? C.val : nothing
89+
shadow = EnzymeRules.needs_shadow(config) ? C.dval : nothing
90+
return EnzymeRules.AugmentedReturn(primal, shadow, cache)
91+
end
92+
function EnzymeRules.reverse(
93+
config::EnzymeRules.RevConfigWidth{1},
94+
func::Const{typeof(TK.braid!)},
95+
::Type{RT},
96+
cache,
97+
C::Annotation{<:AbstractTensorMap},
98+
A::Annotation{<:AbstractTensorMap},
99+
p::Const{<:Index2Tuple},
100+
levels::Const{<:IndexTuple},
101+
α::Annotation{<:Number},
102+
β::Annotation{<:Number},
103+
ba::Const...
104+
) where {RT}
105+
C_cache, A_cache, Ap = cache
106+
Cval = something(C_cache, C.val)
107+
Aval = something(A_cache, A.val)
108+
bavs = map(a -> a.val, ba)
109+
# ΔA
110+
if !isa(A, Const) && !isa(C, Const)
111+
TK.braid_pb(A.dval, Aval, C.dval, C.val, p.val, levels.val, α.val, bavs...)
112+
end
113+
Δαr = pullback_dα(α, C, Ap)
114+
Δβr = pullback_dβ(β, C, Cval)
115+
!isa(C, Const) && pullback_dC!(C.dval, β.val)
116+
return nothing, nothing, nothing, nothing, Δαr, Δβr, map(Returns(nothing), ba)...
117+
end
118+
119+
function EnzymeRules.augmented_primal(
120+
config::EnzymeRules.RevConfigWidth{1},
121+
func::Const{typeof(twist!)},
122+
::Type{RT},
123+
t::Annotation{<:AbstractTensorMap},
124+
inds::Const;
125+
inv::Bool = false
126+
) where {RT}
127+
twist!(t.val, inds.val; inv)
128+
primal = EnzymeRules.needs_primal(config) ? t.val : nothing
129+
shadow = EnzymeRules.needs_shadow(config) ? t.dval : nothing
130+
return EnzymeRules.AugmentedReturn(primal, shadow, nothing)
131+
end
132+
133+
function EnzymeRules.reverse(
134+
config::EnzymeRules.RevConfigWidth{1},
135+
func::Const{typeof(twist!)},
136+
::Type{RT},
137+
cache,
138+
t::Annotation{<:AbstractTensorMap},
139+
inds::Const;
140+
inv::Bool = false
141+
) where {RT}
142+
!isa(t, Const) && twist!(t.dval, inds.val; inv = !inv)
143+
return (nothing, nothing)
144+
end
145+
146+
function EnzymeRules.augmented_primal(
147+
config::EnzymeRules.RevConfigWidth{1},
148+
func::Const{typeof(flip)},
149+
::Type{RT},
150+
t::Annotation{<:AbstractTensorMap},
151+
inds::Const;
152+
inv::Bool = false
153+
) where {RT}
154+
t′ = flip(t.val, inds.val; inv)
155+
dt′ = make_zero(t′)
156+
cache = dt′
157+
primal = EnzymeRules.needs_primal(config) ? t′ : nothing
158+
shadow = EnzymeRules.needs_shadow(config) ? dt′ : nothing
159+
return EnzymeRules.AugmentedReturn(primal, shadow, cache)
160+
end
161+
162+
function EnzymeRules.reverse(
163+
config::EnzymeRules.RevConfigWidth{1},
164+
func::Const{typeof(flip)},
165+
::Type{RT},
166+
cache,
167+
t::Annotation{<:AbstractTensorMap},
168+
inds::Const;
169+
inv::Bool = false,
170+
) where {RT}
171+
dt′ = cache
172+
if !isa(t, Const)
173+
dt′′ = flip(dt′, inds.val; inv = !inv)
174+
add!(t.dval, scalartype(t.dval) <: Real ? real(dt′′) : dt′′)
175+
end
176+
return (nothing, nothing)
177+
end
178+
179+
for insertunit in (:insertleftunit, :insertrightunit)
180+
@eval begin
181+
function EnzymeRules.augmented_primal(
182+
config::EnzymeRules.RevConfigWidth{1},
183+
func::Const{typeof($insertunit)},
184+
::Type{RT},
185+
tsrc::Annotation{<:AbstractTensorMap},
186+
ival::Const{<:Val};
187+
kwargs...
188+
) where {RT}
189+
if tsrc.val isa TensorMap && !get(kwargs, :copy, false) && !isa(tsrc, Const)
190+
tsrc_cache = tsrc.val
191+
tdst = $insertunit(tsrc.val, ival.val; kwargs...)
192+
Δtdst = $insertunit(tsrc.dval, ival.val; kwargs...)
193+
else
194+
tsrc_cache = nothing
195+
tdst = $insertunit(tsrc.val, ival.val; kwargs...)
196+
Δtdst = make_zero(tdst)
197+
end
198+
primal = EnzymeRules.needs_primal(config) ? tdst : nothing
199+
shadow = EnzymeRules.needs_shadow(config) ? Δtdst : nothing
200+
cache = (tsrc_cache, tdst, Δtdst)
201+
return EnzymeRules.AugmentedReturn(primal, shadow, cache)
202+
end
203+
function EnzymeRules.reverse(
204+
config::EnzymeRules.RevConfigWidth{1},
205+
func::Const{typeof($insertunit)},
206+
::Type{RT},
207+
cache,
208+
tsrc::Annotation{<:AbstractTensorMap},
209+
ival::Const{<:Val};
210+
kwargs...
211+
) where {RT}
212+
tsrc_cache, tdst, Δtdst = cache
213+
# note: since data is already shared for <:TensorMap, don't have to do anything here!
214+
if isnothing(tsrc_cache) && !isa(tsrc, Const)
215+
for (c, b) in blocks(Δtdst)
216+
add!(block(tsrc.dval, c), b)
217+
end
218+
end
219+
return (nothing, nothing)
220+
end
221+
end
222+
end
223+
224+
function EnzymeRules.augmented_primal(
225+
config::EnzymeRules.RevConfigWidth{1},
226+
func::Const{typeof(removeunit)},
227+
::Type{RT},
228+
tsrc::Annotation{<:AbstractTensorMap},
229+
ival::Const{<:Val};
230+
kwargs...
231+
) where {RT}
232+
# tdst shares data with tsrc if <:TensorMap & copy=false, in this case we have to deal with correctly
233+
# sharing address spaces
234+
if tsrc.val isa TensorMap && !get(kwargs, :copy, false) && !isa(tsrc, Const)
235+
tsrc_cache = tsrc.val
236+
tdst = removeunit(tsrc.val, ival.val; kwargs...)
237+
Δtdst = removeunit(tsrc.dval, ival.val)
238+
else
239+
tsrc_cache = nothing
240+
tdst = removeunit(tsrc.val, ival.val; kwargs...)
241+
Δtdst = make_zero(tdst)
242+
end
243+
primal = EnzymeRules.needs_primal(config) ? tdst : nothing
244+
shadow = EnzymeRules.needs_shadow(config) ? Δtdst : nothing
245+
cache = (tsrc_cache, tdst, Δtdst)
246+
return EnzymeRules.AugmentedReturn(primal, shadow, cache)
247+
end
248+
249+
function EnzymeRules.reverse(
250+
config::EnzymeRules.RevConfigWidth{1},
251+
func::Const{typeof(removeunit)},
252+
::Type{RT},
253+
cache,
254+
tsrc::Annotation{<:AbstractTensorMap},
255+
ival::Const{<:Val};
256+
kwargs...
257+
) where {RT}
258+
tsrc_cache, tdst, Δtdst = cache
259+
# note: since data for <: TensorMap is already shared, don't have to do anything here!
260+
if isnothing(tsrc_cache) && !isa(tsrc, Const)
261+
for (c, b) in blocks(Δtdst)
262+
add!(block(tsrc.dval, c), b)
263+
end
264+
end
265+
return (nothing, nothing)
266+
end

‎ext/TensorKitMooncakeExt/indexmanipulations.jl‎

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
for transform in (:permute, :transpose)
22
transform! = Symbol(transform, :!)
33
transform_pullback = Symbol(transform!, :_pullback)
4+
transform_pb = Symbol(transform, :_pullback_dA)
45
@eval @is_primitive(
56
DefaultCtx,
67
ReverseMode,
@@ -44,17 +45,7 @@ for transform in (:permute, :transpose)
4445
copy!(C, C_cache)
4546

4647
# ΔA
47-
ip = invperm(linearize(p))
48-
pΔA = TO.repartition(ip, numout(A))
49-
50-
TC = VectorInterface.promote_scale(ΔC, α)
51-
if scalartype(ΔA) <: Real && !(TC <: Real)
52-
ΔAc = TO.tensoralloc_add(TC, ΔC, pΔA, false, Val(false))
53-
TK.$transform!(ΔAc, ΔC, pΔA, conj(α), Zero(), ba...)
54-
add!(ΔA, real(ΔAc))
55-
else
56-
TK.$transform!(ΔA, ΔC, pΔA, conj(α), One(), ba...)
57-
end
48+
TK.$transform_pb(ΔA, A, ΔC, C, p, α, ba...)
5849
ΔAr = NoRData()
5950

6051
Δαr = pullback_dα(α, ΔC, Ap)
@@ -111,18 +102,7 @@ function Mooncake.rrule!!(
111102
function braid!_pullback(::NoRData)
112103
copy!(C, C_cache)
113104

114-
# ΔA
115-
ip = invperm(linearize(p))
116-
pΔA = TO.repartition(ip, numout(A))
117-
ilevels = TupleTools.permute(levels, linearize(p))
118-
TC = VectorInterface.promote_scale(ΔC, α)
119-
if scalartype(ΔA) <: Real && !(TC <: Real)
120-
ΔAc = TO.tensoralloc_add(TC, ΔC, pΔA, false, Val(false))
121-
TK.braid!(ΔAc, ΔC, pΔA, ilevels, conj(α), Zero(), ba...)
122-
add!(ΔA, real(ΔAc))
123-
else
124-
TK.braid!(ΔA, ΔC, pΔA, ilevels, conj(α), One(), ba...)
125-
end
105+
TK.braid_pb(ΔA, A, ΔC, C, p, levels, α, ba...)
126106
ΔAr = NoRData()
127107

128108
Δαr = pullback_dα(α, ΔC, Ap)

‎src/TensorKit.jl‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,4 +285,6 @@ include("planar/planaroperations.jl")
285285
# ------------------------
286286
include("auxiliary/ad.jl")
287287

288+
include("pullbacks/indexmanipulations.jl")
289+
288290
end
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
for transform in (:permute, :transpose)
2+
transform! = Symbol(transform, :!)
3+
transform_pb = Symbol(transform, :_pullback_dA)
4+
@eval function $transform_pb(ΔA, A, ΔC, C, p, α, ba...)
5+
ip = invperm(linearize(p))
6+
pΔA = TO.repartition(ip, numout(A))
7+
TC = VectorInterface.promote_scale(C, α)
8+
if scalartype(ΔA) <: Real && !(TC <: Real)
9+
ΔAc = TO.tensoralloc_add(TC, ΔC, pΔA, false, Val(false))
10+
$transform!(ΔAc, ΔC, pΔA, conj(α), Zero(), ba...)
11+
add!(ΔA, real(ΔAc))
12+
else
13+
$transform!(ΔA, ΔC, pΔA, conj(α), One(), ba...)
14+
end
15+
return
16+
end
17+
end
18+
function braid_pb(ΔA, A, ΔC, C, p, levels, α, ba...)
19+
ip = invperm(linearize(p))
20+
pΔA = TO.repartition(ip, numout(A))
21+
ilevels = TupleTools.permute(levels, linearize(p))
22+
TC = VectorInterface.promote_scale(ΔC, α)
23+
if scalartype(ΔA) <: Real && !(TC <: Real)
24+
ΔAc = TO.tensoralloc_add(TC, ΔC, pΔA, false, Val(false))
25+
braid!(ΔAc, ΔC, pΔA, ilevels, conj(α), Zero(), ba...)
26+
add!(ΔA, real(ΔAc))
27+
else
28+
braid!(ΔA, ΔC, pΔA, ilevels, conj(α), One(), ba...)
29+
end
30+
return
31+
end
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using Test, TestExtras
2+
using TensorKit
3+
using TensorOperations
4+
using Enzyme, EnzymeTestUtils
5+
using Random
6+
7+
spacelist = ad_spacelist(fast_tests)
8+
eltypes = (Float64, ComplexF64)
9+
10+
is_ci = get(ENV, "CI", "false") == "true"
11+
Tαs = is_ci ? (Active,) : (Active, Const)
12+
Tβs = is_ci ? (Active,) : (Active, Const)
13+
14+
@timedtestset "Enzyme - Index Manipulations (braid!):" begin
15+
@timedtestset "$(TensorKit.type_repr(sectortype(eltype(V)))) ($T) Tα $Tα Tβ $Tβ" for V in spacelist, T in eltypes, Tα in Tαs, Tβ in Tβs
16+
atol = default_tol(T)
17+
rtol = default_tol(T)
18+
Vstr = TensorKit.type_repr(sectortype(eltype(V)))
19+
A = randn(T, V[1] ⊗ V[2] ← V[4] ⊗ V[5])
20+
α = randn(T)
21+
β = randn(T)
22+
p = randcircshift(numout(A), numin(A))
23+
levels = Tuple(randperm(numind(A)))
24+
C = randn!(transpose(A, p))
25+
EnzymeTestUtils.test_reverse(TensorKit.braid!, Duplicated, (C, Duplicated), (A, Duplicated), (p, Const), (levels, Const), (α, Tα), (β, Tβ); atol, rtol, testset_name = "braid! V $Vstr Tα $Tα Tβ $Tβ")
26+
if !(T <: Real) && !is_ci
27+
EnzymeTestUtils.test_reverse(TensorKit.braid!, Duplicated, (C, Duplicated), (real(A), Duplicated), (p, Const), (levels, Const), (α, Tα), (β, Tβ); atol, rtol, testset_name = "braid! V $Vstr Tα $Tα Tβ $Tβ")
28+
EnzymeTestUtils.test_reverse(TensorKit.braid!, Duplicated, (C, Duplicated), (A, Duplicated), (p, Const), (levels, Const), (real(α), Tα), (β, Tβ); atol, rtol, testset_name = "braid! V $Vstr Tα $Tα Tβ $Tβ")
29+
EnzymeTestUtils.test_reverse(TensorKit.braid!, Duplicated, (C, Duplicated), (A, Duplicated), (p, Const), (levels, Const), (real(α), Tα), (real(β), Tβ); atol, rtol, testset_name = "braid! V $Vstr Tα $Tα Tβ $Tβ")
30+
end
31+
end
32+
end

0 commit comments

Comments
 (0)