diff --git a/ext/TensorKitChainRulesCoreExt/linalg.jl b/ext/TensorKitChainRulesCoreExt/linalg.jl index b092f0576..80b3d780a 100644 --- a/ext/TensorKitChainRulesCoreExt/linalg.jl +++ b/ext/TensorKitChainRulesCoreExt/linalg.jl @@ -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 diff --git a/test/chainrules/linalg.jl b/test/chainrules/linalg.jl index 3e81dc2ad..472d7edc1 100644 --- a/test/chainrules/linalg.jl +++ b/test/chainrules/linalg.jl @@ -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)