Skip to content

Commit afe0bbb

Browse files
committed
Compute norm only once
1 parent c8460ff commit afe0bbb

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

‎ext/TensorKitChainRulesCoreExt/linalg.jl‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,16 @@ function ChainRulesCore.rrule(::typeof(norm), a::AbstractTensorMap, p::Real = 2)
117117
end
118118

119119
# 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
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
121123
function ChainRulesCore.rrule(::typeof(normalize), a::AbstractTensorMap, p::Real = 2)
122124
p == 2 || error("currently only implemented for p = 2")
123-
y = normalize(a, p)
125+
n = norm(a, p)
126+
y = scale(a, inv(n))
124127
function normalize_pullback(Δy_)
125128
Δy = unthunk(Δy_)
126-
Δa = (Δy - y * real(dot(y, Δy))) / norm(a, p)
129+
Δa = add(Δy, y, -real(dot(y, Δy))) / n
127130
return NoTangent(), ProjectTo(a)(Δa), NoTangent()
128131
end
129132
normalize_pullback(::AbstractZero) = NoTangent(), ZeroTangent(), NoTangent()

0 commit comments

Comments
 (0)