Skip to content

Commit 04d6cb0

Browse files
kshyattlkdvos
andauthored
Add rrule for normalize on AbstractTensorMap (#637)
* Add rrule for normalize on AbstractTensorMap * Compute norm only once * Update ext/TensorKitChainRulesCoreExt/linalg.jl Co-authored-by: Lukas Devos <ldevos98@gmail.com> * Make sure the primal is actually identical * You only inv once --------- Co-authored-by: Lukas Devos <ldevos98@gmail.com>
1 parent 7509eeb commit 04d6cb0

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

‎ext/TensorKitChainRulesCoreExt/linalg.jl‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,24 @@ 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 norm is computed once in the forward pass and reused in the pullback
121+
# TODO revisit this once VectorInterface supports supplying a GPU vector for the output
122+
# of norm and inner
123+
function ChainRulesCore.rrule(::typeof(normalize), a::AbstractTensorMap, p::Real = 2)
124+
p == 2 || error("currently only implemented for p = 2")
125+
n = norm(a, p)
126+
invn = inv(n)
127+
y = normalize(a, p)
128+
function normalize_pullback(Δy_)
129+
Δy = unthunk(Δy_)
130+
Δa = add(Δy, y, -real(dot(y, Δy)) * invn, invn)
131+
return NoTangent(), ProjectTo(a)(Δa), NoTangent()
132+
end
133+
normalize_pullback(::AbstractZero) = NoTangent(), ZeroTangent(), NoTangent()
134+
return y, normalize_pullback
135+
end
136+
119137
function ChainRulesCore.rrule(::typeof(inv), A::AbstractTensorMap)
120138
Ainv = inv(A)
121139
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)