Skip to content

Commit 5c7b1ac

Browse files
lkdvosclaude
andcommitted
Add Enzyme rules for planartrace!
Enzyme cannot differentiate through the threaded `taskforeach` in the new trace kernel, so `planartrace!` now has forward and reverse rules, as for the index manipulations. The pullback `planartrace_pullback_ΔA!` reuses the cached `TraceTransformer`: it adds `ΔC` to the traced diagonal of every source subblock with coefficients `conj(α * U[i, j]) * dim(cᵢ) / dim(cⱼ)`, going through the subblocks such that adjoint tensors are supported, and falls back to `trace_permute_pullback_ΔA!` for bosonic sectors. `treetracer` is marked inactive. The Enzyme `planartrace!` test skipped every draw without a remaining leg or traced pair, which in practice skipped (almost) all of them. It now always draws at least one of each, retries draws whose multifusion spaces have mismatched units, and also compares the pullback of adjoint tensors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 388c35e commit 5c7b1ac

6 files changed

Lines changed: 191 additions & 15 deletions

File tree

‎docs/src/Changelog.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
2323
### Added
2424

2525
- Re-export `NamedSector` and `@NamedSector` from TensorKitSectors
26+
- Enzyme rules for `planartrace!`, with a pullback that also supports adjoint tensors
2627

2728
### Changed
2829

‎ext/TensorKitEnzymeExt/TensorKitEnzymeExt.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,6 @@ include("utility.jl")
3030
include("linalg.jl")
3131
include("indexmanipulations.jl")
3232
include("tensoroperations.jl")
33+
include("planaroperations.jl")
3334

3435
end
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# planartrace!
2+
# ------------
3+
function EnzymeRules.augmented_primal(
4+
config::EnzymeRules.RevConfigWidth{1},
5+
func::Const{typeof(TK.planartrace!)},
6+
::Type{RT},
7+
C::Annotation{<:AbstractTensorMap},
8+
A::Annotation{<:AbstractTensorMap},
9+
p::Const{<:Index2Tuple},
10+
q::Const{<:Index2Tuple},
11+
α::Annotation{<:Number},
12+
β::Annotation{<:Number},
13+
backend::Const,
14+
allocator::Const
15+
) where {RT}
16+
C_cache = !isa(β, Const) ? copy(C.val) : nothing
17+
# if we need to compute Δα, store the trace of A instead of recomputing it in the pullback
18+
At = if !isa(α, Const)
19+
At = TK.planartrace!(zerovector(C.val), A.val, p.val, q.val, One(), Zero(), backend.val, allocator.val)
20+
add!(C.val, At, α.val, β.val)
21+
At
22+
else
23+
TK.planartrace!(C.val, A.val, p.val, q.val, α.val, β.val, backend.val, allocator.val)
24+
nothing
25+
end
26+
cache = (C_cache, At)
27+
primal = EnzymeRules.needs_primal(config) ? C.val : nothing
28+
shadow = EnzymeRules.needs_shadow(config) ? C.dval : nothing
29+
return EnzymeRules.AugmentedReturn(primal, shadow, cache)
30+
end
31+
32+
function EnzymeRules.reverse(
33+
config::EnzymeRules.RevConfigWidth{1},
34+
func::Const{typeof(TK.planartrace!)},
35+
::Type{RT},
36+
cache,
37+
C::Annotation{<:AbstractTensorMap},
38+
A::Annotation{<:AbstractTensorMap},
39+
p::Const{<:Index2Tuple},
40+
q::Const{<:Index2Tuple},
41+
α::Annotation{<:Number},
42+
β::Annotation{<:Number},
43+
backend::Const,
44+
allocator::Const
45+
) where {RT}
46+
C_cache, At = cache
47+
Cval = something(C_cache, C.val)
48+
# the pullback of A is linear, so only the spaces of A are needed
49+
if !is_inactive(config, A) && !is_inactive(config, C)
50+
TK.planartrace_pullback_ΔA!(A.dval, C.dval, A.val, p.val, q.val, α.val, backend.val, allocator.val)
51+
end
52+
Δα = pullback_dα(α, C, At)
53+
Δβ = pullback_dβ(β, C, Cval)
54+
!is_inactive(config, C) && pullback_dC!(C.dval, β.val)
55+
return nothing, nothing, nothing, nothing, Δα, Δβ, nothing, nothing
56+
end
57+
58+
function EnzymeRules.forward(
59+
config::EnzymeRules.FwdConfigWidth{1},
60+
func::Const{typeof(TK.planartrace!)},
61+
::Type{RT},
62+
C::Annotation{<:AbstractTensorMap},
63+
A::Annotation{<:AbstractTensorMap},
64+
p::Annotation{<:Index2Tuple},
65+
q::Annotation{<:Index2Tuple},
66+
α::Annotation{<:Number},
67+
β::Annotation{<:Number},
68+
backend::Const,
69+
allocator::Const
70+
) where {RT}
71+
# ΔC′ = ΔC*β + C*Δβ + tr(A)*Δα + tr(ΔA)*α
72+
if !isa(C, Const)
73+
if isa(β, Const)
74+
scale!(C.dval, β.val)
75+
else
76+
add!(C.dval, C.val, β.dval, β.val)
77+
end
78+
!isa(α, Const) && TK.planartrace!(C.dval, A.val, p.val, q.val, α.dval, One(), backend.val, allocator.val)
79+
!isa(A, Const) && TK.planartrace!(C.dval, A.dval, p.val, q.val, α.val, One(), backend.val, allocator.val)
80+
end
81+
TK.planartrace!(C.val, A.val, p.val, q.val, α.val, β.val, backend.val, allocator.val)
82+
if EnzymeRules.needs_primal(config) && EnzymeRules.needs_shadow(config)
83+
return C
84+
elseif EnzymeRules.needs_primal(config)
85+
return C.val
86+
elseif EnzymeRules.needs_shadow(config) && !isa(C, Const)
87+
return C.dval
88+
elseif EnzymeRules.needs_shadow(config) && isa(C, Const)
89+
return Enzyme.make_zero(C.val)
90+
else
91+
return nothing
92+
end
93+
end

‎ext/TensorKitEnzymeExt/utility.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ end
150150
@inline EnzymeRules.inactive(::typeof(TensorKit.product_transform), ::Any...) = nothing
151151
@inline EnzymeRules.inactive(::typeof(TensorKit.treetransposer), ::Any...) = nothing
152152
@inline EnzymeRules.inactive(::typeof(TensorKit.treebraider), ::Any...) = nothing
153+
@inline EnzymeRules.inactive(::typeof(TensorKit.treetracer), ::Any...) = nothing
153154
@inline EnzymeRules.inactive(::typeof(TensorKit.insertleftunit), ::HomSpace, ::Any) = nothing
154155
@inline EnzymeRules.inactive(::typeof(TensorKit.insertrightunit), ::HomSpace, ::Any) = nothing
155156
@inline EnzymeRules.inactive(::typeof(TensorKit.removeunit), ::HomSpace, ::Any) = nothing

‎src/pullbacks/tensoroperations.jl‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,59 @@ function trace_permute_pullback_ΔA!(
6464
)
6565
return nothing
6666
end
67+
68+
# The planar trace adds `α * U[i, j]` times the dense trace of every source subblock `j` to
69+
# destination subblock `i`. Since `inner` weighs every subblock with the dimension of its coupled
70+
# sector, the adjoint adds `ΔC` to the traced diagonal of every source subblock, with coefficients
71+
# `conj(α * U[i, j]) * dim(cᵢ) / dim(cⱼ)`.
72+
function planartrace_pullback_ΔA!(
73+
ΔA, ΔC, A::AbstractTensorMap, p, q, α, backend, allocator
74+
)
75+
BraidingStyle(sectortype(A)) == Bosonic() &&
76+
return trace_permute_pullback_ΔA!(ΔA, ΔC, A, p, q, α, backend)
77+
transformer = treetracer(storagetype(ΔC), space(ΔC), space(A), p, q)
78+
T = promote_type(scalartype(ΔC), scalartype(α), _coefficienttype(transformer))
79+
if T <: Real || !(scalartype(ΔA) <: Real)
80+
_planartrace_pullback_ΔA!(ΔA, ΔC, transformer, p, q, α, backend, allocator)
81+
else
82+
ΔAc = zerovector(ΔA, T)
83+
_planartrace_pullback_ΔA!(ΔAc, ΔC, transformer, p, q, α, backend, allocator)
84+
add!(ΔA, real(ΔAc))
85+
end
86+
return nothing
87+
end
88+
89+
_coefficienttype(::TraceTransformer{T}) where {T} = T
90+
91+
function _planartrace_pullback_ΔA!(
92+
ΔA, ΔC, transformer::TraceTransformer, (p₁, p₂), (q₁, q₂), α, backend, allocator
93+
)
94+
lp = (p₁..., p₂...)
95+
dims_dst = [dim(f₁.coupled) for (f₁, _) in fusiontrees(ΔC)]
96+
dims_src = [dim(f₁.coupled) for (f₁, _) in fusiontrees(ΔA)]
97+
dst, src = _transform_subblocks(ΔC, ΔA, transformer)
98+
for (U, inds_dst, inds_src) in transformer.data, (j, isrc) in enumerate(inds_src)
99+
# the traced diagonal of the source subblock, with the remaining legs permuted by `p`
100+
a = StridedView(src[isrc])
101+
sz, str = size(a), strides(a)
102+
sz_traced = TupleTools.getindices(sz, q₁)
103+
str_traced = TupleTools.getindices(str, q₁) .+ TupleTools.getindices(str, q₂)
104+
diag = StridedView(
105+
parent(a), (TupleTools.getindices(sz, lp)..., sz_traced...),
106+
(TupleTools.getindices(str, lp)..., str_traced...), a.offset, a.op
107+
)
108+
pdiag = (ntuple(identity, ndims(diag)), ())
109+
for (i, idst) in enumerate(inds_dst)
110+
iszero(U[i, j]) && continue
111+
# the destination subblock, constant along the traced legs
112+
c = StridedView(dst[idst])
113+
ΔCi = StridedView(
114+
parent(c), (size(c)..., sz_traced...), (strides(c)..., map(zero, sz_traced)...),
115+
c.offset, c.op
116+
)
117+
coeff = conj(α * U[i, j]) * (dims_dst[idst] / dims_src[isrc])
118+
TO.tensoradd!(diag, ΔCi, pdiag, false, coeff, One(), backend, allocator)
119+
end
120+
end
121+
return ΔA
122+
end

‎test/enzyme/trace.jl‎

Lines changed: 39 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,11 @@ TAs = is_ci ? (Duplicated,) : (Const, Duplicated)
5757
end
5858
end
5959
@timedtestset "planartrace!" begin
60-
for _ in 1:5
61-
k1 = rand(0:2)
62-
k2 = rand(0:1)
60+
# a random planar trace with at least one remaining leg and one traced pair, or `nothing`
61+
# for multifusion sectors whose random spaces have mismatched units, or empty output
62+
function randplanartrace()
63+
k1 = rand(1:2)
64+
k2 = 1
6365
V1 = map(v -> rand(Bool) ? v' : v, rand(V, k1))
6466
V2 = map(v -> rand(Bool) ? v' : v, rand(V, k2))
6567
V3 = prod(x -> x ⊗ x', V2[1:k2]; init = one(V[1]))
@@ -69,19 +71,41 @@ TAs = is_ci ? (Duplicated,) : (Const, Duplicated)
6971
(_p, _q) = randcircshift(k′, k1 + 2k2 - k′, k1)
7072
p = _repartition(_p, rand(0:k1))
7173
q = (tuple(_q[1:2:end]...), tuple(_q[2:2:end]...))
72-
if !all(isempty, p) && !all(isempty, q)
73-
α = randn(T)
74-
β = randn(T)
75-
ip = _repartition(invperm(linearize((_p, _q))), k′)
76-
A = randn(T, permute(prod(V1) ⊗ V3 ← V4, ip))
77-
C = randn!(TensorOperations.tensoralloc_add(T, A, p, false, Val(false)))
78-
for Tα in (Const, Active), Tβ in (Const, Active)
79-
EnzymeTestUtils.test_reverse(TensorKit.planartrace!, Duplicated, (C, Duplicated), (A, Duplicated), (p, Const), (q, Const), (α, Tα), (β, Tβ), (TensorOperations.DefaultBackend(), Const), (TensorOperations.DefaultAllocator(), Const); atol, rtol, testset_name = "planartrace reverse Tα $Tα Tβ $Tβ")
80-
end
81-
for Tα in (Const, Duplicated), Tβ in (Const, Duplicated)
82-
EnzymeTestUtils.test_forward(TensorKit.planartrace!, Duplicated, (C, Duplicated), (A, Duplicated), (p, Const), (q, Const), (α, Tα), (β, Tβ), (TensorOperations.DefaultBackend(), Const), (TensorOperations.DefaultAllocator(), Const); atol, rtol, testset_name = "planartrace forward Tα $Tα Tβ $Tβ")
83-
end
74+
ip = _repartition(invperm(linearize((_p, _q))), k′)
75+
W = try
76+
permute(prod(V1) ⊗ V3 ← V4, ip)
77+
catch e
78+
e isa SpaceMismatch || rethrow()
79+
return nothing
8480
end
81+
return dim(TensorKit.select(W, p)) > 0 ? (W, p, q) : nothing
82+
end
83+
for _ in 1:3
84+
trace = nothing
85+
for _ in 1:50
86+
trace = randplanartrace()
87+
isnothing(trace) || break
88+
end
89+
isnothing(trace) && continue
90+
W, p, q = trace
91+
A = randn(T, W)
92+
α = randn(T)
93+
β = randn(T)
94+
C = randn!(TensorOperations.tensoralloc_add(T, A, p, false, Val(false)))
95+
for Tα in rTαs, Tβ in rTβs
96+
EnzymeTestUtils.test_reverse(TensorKit.planartrace!, Duplicated, (C, Duplicated), (A, Duplicated), (p, Const), (q, Const), (α, Tα), (β, Tβ), (TensorOperations.DefaultBackend(), Const), (TensorOperations.DefaultAllocator(), Const); atol, rtol, testset_name = "planartrace reverse Tα $Tα Tβ $Tβ")
97+
end
98+
for Tα in fTαs, Tβ in fTβs
99+
EnzymeTestUtils.test_forward(TensorKit.planartrace!, Duplicated, (C, Duplicated), (A, Duplicated), (p, Const), (q, Const), (α, Tα), (β, Tβ), (TensorOperations.DefaultBackend(), Const), (TensorOperations.DefaultAllocator(), Const); atol, rtol, testset_name = "planartrace forward Tα $Tα Tβ $Tβ")
100+
end
101+
# the pullback of adjoint tensors goes through their subblocks
102+
ba = (TensorOperations.DefaultBackend(), TensorOperations.DefaultAllocator())
103+
ΔC = randn!(similar(C))
104+
ΔA = zerovector(A)
105+
TensorKit.planartrace_pullback_ΔA!(ΔA, ΔC, A, p, q, α, ba...)
106+
ΔA′ = zerovector(copy(A'))'
107+
TensorKit.planartrace_pullback_ΔA!(ΔA′, copy(ΔC')', copy(A')', p, q, α, ba...)
108+
@test copy(ΔA′) ≈ ΔA
85109
end
86110
end
87111
end

0 commit comments

Comments
 (0)