Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions ext/TensorKitChainRulesCoreExt/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,23 @@ function ChainRulesCore.rrule(::typeof(norm), a::AbstractTensorMap, p::Real = 2)
return n, norm_pullback
end

# needed since GPU tensors have a specialized `normalize` that AD cannot trace through;
# the norm is computed once in the forward pass and reused in the pullback
# TODO revisit this once VectorInterface supports supplying a GPU vector for the output
# of norm and inner
function ChainRulesCore.rrule(::typeof(normalize), a::AbstractTensorMap, p::Real = 2)
p == 2 || error("currently only implemented for p = 2")
n = norm(a, p)
y = scale(a, inv(n))
function normalize_pullback(Δy_)
Δy = unthunk(Δy_)
Δa = add(Δy, y, -real(dot(y, Δy)) / n, inv(n))
return NoTangent(), ProjectTo(a)(Δa), NoTangent()
end
normalize_pullback(::AbstractZero) = NoTangent(), ZeroTangent(), NoTangent()
return y, normalize_pullback
end

function ChainRulesCore.rrule(::typeof(inv), A::AbstractTensorMap)
Ainv = inv(A)
inv_pullback = let Ainv = Ainv
Expand Down
1 change: 1 addition & 0 deletions test/chainrules/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ for V in spacelist
A = randn(T, V[1] ⊗ V[2] ← (V[3] ⊗ V[4] ⊗ V[5])')
test_rrule(LinearAlgebra.adjoint, A; atol, rtol)
test_rrule(LinearAlgebra.norm, A, 2; atol, rtol)
test_rrule(LinearAlgebra.normalize, A, 2; atol, rtol)

B = randn(T, space(A))
test_rrule(LinearAlgebra.dot, A, B; atol, rtol)
Expand Down
Loading