Skip to content

Commit 04cfea3

Browse files
committed
Add rrule for normalize on AbstractTensorMap
1 parent 7509eeb commit 04cfea3

2 files changed

Lines changed: 15 additions & 0 deletions

File tree

‎ext/TensorKitChainRulesCoreExt/linalg.jl‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,20 @@ function ChainRulesCore.rrule(::typeof(norm), a::AbstractTensorMap, p::Real = 2)
116116
return n, norm_pullback
117117
end
118118

119+
# needed since GPU tensors have a specialized `normalize` that AD cannot trace through;
120+
# the forward pass reuses it, the norm is only computed in the pullback
121+
function ChainRulesCore.rrule(::typeof(normalize), a::AbstractTensorMap, p::Real = 2)
122+
p == 2 || error("currently only implemented for p = 2")
123+
y = normalize(a, p)
124+
function normalize_pullback(Δy_)
125+
Δy = unthunk(Δy_)
126+
Δa = (Δy - y * real(dot(y, Δy))) / norm(a, p)
127+
return NoTangent(), ProjectTo(a)(Δa), NoTangent()
128+
end
129+
normalize_pullback(::AbstractZero) = NoTangent(), ZeroTangent(), NoTangent()
130+
return y, normalize_pullback
131+
end
132+
119133
function ChainRulesCore.rrule(::typeof(inv), A::AbstractTensorMap)
120134
Ainv = inv(A)
121135
inv_pullback = let Ainv = Ainv

‎test/chainrules/linalg.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ for V in spacelist
163163
A = randn(T, V[1] ⊗ V[2] ← (V[3] ⊗ V[4] ⊗ V[5])')
164164
test_rrule(LinearAlgebra.adjoint, A; atol, rtol)
165165
test_rrule(LinearAlgebra.norm, A, 2; atol, rtol)
166+
test_rrule(LinearAlgebra.normalize, A, 2; atol, rtol)
166167

167168
B = randn(T, space(A))
168169
test_rrule(LinearAlgebra.dot, A, B; atol, rtol)

0 commit comments

Comments
 (0)