diff --git a/ext/MatrixAlgebraKitAMDGPUExt/MatrixAlgebraKitAMDGPUExt.jl b/ext/MatrixAlgebraKitAMDGPUExt/MatrixAlgebraKitAMDGPUExt.jl index e20b81da5..458cc691a 100644 --- a/ext/MatrixAlgebraKitAMDGPUExt/MatrixAlgebraKitAMDGPUExt.jl +++ b/ext/MatrixAlgebraKitAMDGPUExt/MatrixAlgebraKitAMDGPUExt.jl @@ -9,7 +9,7 @@ using MatrixAlgebraKit: default_qr_algorithm, default_lq_algorithm, default_svd_ import MatrixAlgebraKit: geqrf!, ungqr!, unmqr!, gesvd!, gesdd!, gesvdx!, gesvdj! import MatrixAlgebraKit: gesvdj_batched!, gesdd_batched!, gesvd_batched!, gesvdx_batched! import MatrixAlgebraKit: heevj!, heevd!, heev!, heevx! -import MatrixAlgebraKit: _sylvester, svd_rank, svd_pullback! +import MatrixAlgebraKit: svd_rank, svd_pullback! using AMDGPU using LinearAlgebra using LinearAlgebra: BlasFloat @@ -165,9 +165,4 @@ function MatrixAlgebraKit._mul_herm!(C::StridedROCMatrix{T}, A::StridedROCMatrix return C end -function _sylvester(A::AnyROCMatrix, B::AnyROCMatrix, C::AnyROCMatrix) - hX = sylvester(collect(A), collect(B), collect(C)) - return ROCArray(hX) -end - end diff --git a/ext/MatrixAlgebraKitCUDAExt/MatrixAlgebraKitCUDAExt.jl b/ext/MatrixAlgebraKitCUDAExt/MatrixAlgebraKitCUDAExt.jl index 0c04bb235..8edc550b0 100644 --- a/ext/MatrixAlgebraKitCUDAExt/MatrixAlgebraKitCUDAExt.jl +++ b/ext/MatrixAlgebraKitCUDAExt/MatrixAlgebraKitCUDAExt.jl @@ -9,7 +9,7 @@ using MatrixAlgebraKit: default_qr_algorithm, default_lq_algorithm, default_svd_ import MatrixAlgebraKit: geqrf!, ungqr!, unmqr!, gesvd!, gesvdp!, gesvdr!, gesvdj! import MatrixAlgebraKit: gesvdj_batched! import MatrixAlgebraKit: heevj!, heevd!, geev! -import MatrixAlgebraKit: _gpu_Xgesvdr!, _sylvester +import MatrixAlgebraKit: _gpu_Xgesvdr! using CUDA, CUDA.cuBLAS using CUDA: i32 using LinearAlgebra @@ -88,11 +88,4 @@ function MatrixAlgebraKit._mul_herm!(C::StridedCuMatrix{T}, A::StridedCuMatrix{T return C end -function _sylvester(A::AnyCuMatrix, B::AnyCuMatrix, C::AnyCuMatrix) - # https://github.com/JuliaGPU/CUDA.jl/issues/3021 - # to add native sylvester to CUDA - hX = sylvester(collect(A), collect(B), collect(C)) - return CuArray(hX) -end - end diff --git a/ext/MatrixAlgebraKitEnzymeExt/MatrixAlgebraKitEnzymeExt.jl b/ext/MatrixAlgebraKitEnzymeExt/MatrixAlgebraKitEnzymeExt.jl index bdbf82347..d481027e6 100644 --- a/ext/MatrixAlgebraKitEnzymeExt/MatrixAlgebraKitEnzymeExt.jl +++ b/ext/MatrixAlgebraKitEnzymeExt/MatrixAlgebraKitEnzymeExt.jl @@ -56,8 +56,6 @@ for (f, pb) in ( (lq_compact!, lq_pullback!), (eig_full!, eig_pullback!), (eigh_full!, eigh_pullback!), - (left_polar!, left_polar_pullback!), - (right_polar!, right_polar_pullback!), ) @eval begin function EnzymeRules.augmented_primal( @@ -118,9 +116,103 @@ for (f, pb) in ( end end +# For real matrices, Enzyme differentiates SVD-based polar through the SVD rules. For complex +# matrices it can't yet. +const PolarAlgs = Union{MatrixAlgebraKit.DiagonalAlgorithm, MatrixAlgebraKit.PolarNewton} +for (f, pb, pf) in ( + (:left_polar!, :left_polar_pullback!, :left_polar_pushforward!), + (:right_polar!, :right_polar_pullback!, :right_polar_pushforward!), + ), (AT, AlgT) in ( + (:Annotation, :PolarAlgs), + (:(Annotation{<:AbstractMatrix{<:Complex}}), :(MatrixAlgebraKit.PolarViaSVD)), + ) + @eval begin + function EnzymeRules.augmented_primal( + config::EnzymeRules.RevConfigWidth{1}, + func::Const{typeof($f)}, + ::Type{RT}, + A::$AT, + arg::Annotation{Tuple{TA, TB}}, + alg::Const{<:$AlgT}, + ) where {RT, TA, TB} + # A is overwritten in the primal, but not used in the pullback, so we do not need to cache it. + ret = func.val(A.val, arg.val, alg.val) + # if arg.val === ret, the annotation must be Duplicated or DuplicatedNoNeed + # if arg isa Const, ret may still be modified further down the call graph so we should + # copy it to protect ourselves + A_is_arg1 = !isa(A, Const) && has_equal_storage(A.val, arg.val[1]) + A_is_arg2 = !isa(A, Const) && has_equal_storage(A.val, arg.val[2]) + A_is_arg = A_is_arg1 || A_is_arg2 + cache_arg = arg.val !== ret || A_is_arg || EnzymeRules.overwritten(config)[3] ? copy.(ret) : ret + dret = if EnzymeRules.needs_shadow(config) && ((TA == Nothing && TB == Nothing) || isa(arg, Const)) + make_zero.(ret) + elseif EnzymeRules.needs_shadow(config) + arg.dval + else + nothing + end + primal = EnzymeRules.needs_primal(config) ? ret : nothing + return EnzymeRules.AugmentedReturn(primal, dret, (cache_arg, dret)) + end + function EnzymeRules.reverse( + config::EnzymeRules.RevConfigWidth{1}, + func::Const{typeof($f)}, + ::Type{RT}, + cache, + A::$AT, + arg::Annotation{Tuple{TA, TB}}, + alg::Const{<:$AlgT}, + ) where {RT, TA, TB} + cache_arg, darg = cache + # A is not used in the pullback; since we have destroyed A, we insert Aval = nothing + # to trigger an error in case the pushfward is modified to directly use A + Aval = nothing + A_is_arg1 = !isa(A, Const) && has_equal_storage(A.dval, arg.dval[1]) + A_is_arg2 = !isa(A, Const) && has_equal_storage(A.dval, arg.dval[2]) + A_is_arg = A_is_arg1 || A_is_arg2 + argval = cache_arg + if !isa(A, Const) + ΔA = A_is_arg ? make_zero(A.dval) : A.dval + $pb(ΔA, Aval, argval, darg) + A_is_arg && (A.dval .= ΔA) + end + if !isa(arg, Const) + A_is_arg1 || make_zero!(arg.dval[1]) + A_is_arg2 || make_zero!(arg.dval[2]) + end + return (nothing, nothing, nothing) + end + function EnzymeRules.forward( + config::EnzymeRules.FwdConfigWidth{1}, + func::Const{typeof($f)}, + ::Type{RT}, + A::$AT, + arg::Annotation, + alg::Annotation{<:$AlgT}, + ) where {RT} + A_is_arg1 = !isa(A, Const) && has_equal_storage(A.val, arg.val[1]) + A_is_arg2 = !isa(A, Const) && has_equal_storage(A.val, arg.val[2]) + A_is_arg = A_is_arg1 || A_is_arg2 + $f(A.val, arg.val, alg.val) + if !isa(A, Const) && !isa(arg, Const) + $pf(A.dval, A.val, arg.val, arg.dval) + end + !A_is_arg && make_zero!(A.dval) + if EnzymeRules.needs_primal(config) && EnzymeRules.needs_shadow(config) + return arg + elseif EnzymeRules.needs_primal(config) + return arg.val + elseif EnzymeRules.needs_shadow(config) + return arg.dval + else + return nothing + end + end + end +end + + for (f, pf) in ( - (:right_polar!, :right_polar_pushforward!), - (:left_polar!, :left_polar_pushforward!), (:eigh_full!, :eigh_pushforward!), (:eig_full!, :eig_pushforward!), (:qr_full!, :qr_pushforward!), @@ -250,10 +342,7 @@ for f! in (:svd_compact!, :svd_full!) ) where {RT, TU, TS, TVᴴ} # A is overwritten in the primal, but not used in the pullback, so we do not need to cache it. ret = func.val(A.val, USVᴴ.val, alg.val) - # if USVᴴ.val == ret, the annotation must be Duplicated or DuplicatedNoNeed - # if USVᴴ isa Const, ret may still be modified further down the call graph so we should - # copy it to protect ourselves - cache_USVᴴ = (USVᴴ.val !== ret) || EnzymeRules.overwritten(config)[3] ? copy.(ret) : ret + cache_USVᴴ = copy.(ret) # the USVᴴ may be nothing for eltypes handled by GenericLinearAlgebra dret = if EnzymeRules.needs_shadow(config) ((TU == TS == TVᴴ == Nothing) || isa(USVᴴ, Const)) ? make_zero(ret) : USVᴴ.dval diff --git a/ext/MatrixAlgebraKitMooncakeExt/MatrixAlgebraKitMooncakeExt.jl b/ext/MatrixAlgebraKitMooncakeExt/MatrixAlgebraKitMooncakeExt.jl index c3e7f4b1b..61d1c1372 100644 --- a/ext/MatrixAlgebraKitMooncakeExt/MatrixAlgebraKitMooncakeExt.jl +++ b/ext/MatrixAlgebraKitMooncakeExt/MatrixAlgebraKitMooncakeExt.jl @@ -49,8 +49,6 @@ for (f!, f, pb, adj) in ( (:lq_compact!, :lq_compact, :lq_pullback!, :lq_adjoint), (:eig_full!, :eig_full, :eig_pullback!, :eig_adjoint), (:eigh_full!, :eigh_full, :eigh_pullback!, :eigh_adjoint), - (:left_polar!, :left_polar, :left_polar_pullback!, :left_polar_adjoint), - (:right_polar!, :right_polar, :right_polar_pullback!, :right_polar_adjoint), ) @eval begin @is_primitive Mooncake.DefaultCtx Mooncake.ReverseMode Tuple{typeof($f!), Any, Tuple{<:Any, <:Any}, MatrixAlgebraKit.AbstractAlgorithm} @@ -111,9 +109,96 @@ for (f!, f, pb, adj) in ( end end +# let Mooncake make its own rules for the PolarViaSVD case +const PolarAlgs = Union{MatrixAlgebraKit.PolarNewton, MatrixAlgebraKit.DiagonalAlgorithm} +for (f!, f, pb, pf, adj) in ( + (:left_polar!, :left_polar, :left_polar_pullback!, :left_polar_pushforward!, :left_polar_adjoint), + (:right_polar!, :right_polar, :right_polar_pullback!, :right_polar_pushforward!, :right_polar_adjoint), + ) + @eval begin + @is_primitive Mooncake.DefaultCtx Mooncake.ReverseMode Tuple{typeof($f!), Any, Tuple{<:Any, <:Any}, PolarAlgs} + function Mooncake.rrule!!(::CoDual{typeof($f!)}, A_dA::CoDual, args_dargs::CoDual, alg_dalg::CoDual{<:PolarAlgs}) + A, dA = arrayify(A_dA) + args = Mooncake.primal(args_dargs) + dargs = Mooncake.tangent(args_dargs) + arg1, darg1 = arrayify(args[1], dargs[1]) + arg2, darg2 = arrayify(args[2], dargs[2]) + Ac = copy(A) + arg1c = copy(arg1) + arg2c = copy(arg2) + $f!(A, args, Mooncake.primal(alg_dalg)) + function $adj(::NoRData) + # DON'T copy Ac to A if A === one + # of the output args -- this can + # mess up the pullback because + # generally the args are used there + if !(has_equal_storage(A, arg1) || has_equal_storage(A, arg2)) + copy!(A, Ac) + $pb(dA, A, (arg1, arg2), (darg1, darg2)) + else + ΔA = zero(A) + $pb(ΔA, Ac, (arg1, arg2), (darg1, darg2)) + dA .= ΔA + end + if has_equal_storage(A, arg1) + zero!(darg2) + elseif has_equal_storage(A, arg2) + zero!(darg1) + else + zero!(darg1) + zero!(darg2) + end + copy!(arg2, arg2c) + copy!(arg1, arg1c) + return ntuple(Returns(NoRData()), 4) + end + return args_dargs, $adj + end + @is_primitive Mooncake.DefaultCtx Mooncake.ReverseMode Tuple{typeof($f), Any, PolarAlgs} + function Mooncake.rrule!!(::CoDual{typeof($f)}, A_dA::CoDual, alg_dalg::CoDual{<:PolarAlgs}) + A, dA = arrayify(A_dA) + output = $f(A, Mooncake.primal(alg_dalg)) + output_codual = Mooncake.zero_fcodual(output) + function $adj(::NoRData) + arg1, arg2 = Mooncake.primal(output_codual) + darg1_, darg2_ = Mooncake.tangent(output_codual) + arg1, darg1 = arrayify(arg1, darg1_) + arg2, darg2 = arrayify(arg2, darg2_) + $pb(dA, A, (arg1, arg2), (darg1, darg2)) + zero!(darg1) + zero!(darg2) + return NoRData(), NoRData(), NoRData() + end + return output_codual, $adj + end + @is_primitive Mooncake.DefaultCtx Mooncake.ForwardMode Tuple{typeof($f!), Any, Tuple{<:Any, <:Any}, PolarAlgs} + function Mooncake.frule!!(::Dual{typeof($f!)}, A_dA::Dual, args_dargs::Dual, alg_dalg::Dual{<:PolarAlgs}) + A, dA = arrayify(A_dA) + args = Mooncake.primal(args_dargs) + dargs = Mooncake.tangent(args_dargs) + arg1, darg1 = arrayify(args[1], dargs[1]) + arg2, darg2 = arrayify(args[2], dargs[2]) + $f!(A, args, Mooncake.primal(alg_dalg)) + # A is not used in the pushforward; since we have destroyed A, we insert A = nothing + # to trigger an error in case the pushfward is modified to directly use A + $pf(dA, nothing, (arg1, arg2), (darg1, darg2)) + return args_dargs + end + @is_primitive Mooncake.DefaultCtx Mooncake.ForwardMode Tuple{typeof($f), Any, PolarAlgs} + function Mooncake.frule!!(::Dual{typeof($f)}, A_dA::Dual, alg_dalg::Dual{<:PolarAlgs}) + A, dA = arrayify(A_dA) + output = $f(A, Mooncake.primal(alg_dalg)) + doutput = Mooncake.zero_tangent(output) + output_dual = Dual(output, doutput) + arg1, darg1 = arrayify(output[1], doutput[1]) + arg2, darg2 = arrayify(output[2], doutput[2]) + $pf(dA, A, (arg1, arg2), (darg1, darg2)) + return output_dual + end + end +end + for (f!, f, pf) in ( - (:left_polar!, :left_polar, :left_polar_pushforward!), - (:right_polar!, :right_polar, :right_polar_pushforward!), (:qr_full!, :qr_full, :qr_pushforward!), (:qr_compact!, :qr_compact, :qr_pushforward!), (:lq_full!, :lq_full, :lq_pushforward!), diff --git a/src/MatrixAlgebraKit.jl b/src/MatrixAlgebraKit.jl index 42b3f82e2..c6157aa68 100644 --- a/src/MatrixAlgebraKit.jl +++ b/src/MatrixAlgebraKit.jl @@ -3,7 +3,7 @@ module MatrixAlgebraKit using LinearAlgebra: LinearAlgebra using LinearAlgebra: norm # TODO: eleminate if we use VectorInterface.jl? using LinearAlgebra: mul!, rmul!, lmul!, adjoint!, rdiv!, ldiv! -using LinearAlgebra: sylvester, lu!, diagm +using LinearAlgebra: lu!, diagm using LinearAlgebra: isposdef, issymmetric using LinearAlgebra: Diagonal, Hermitian, diag, diagind, isdiag using LinearAlgebra: UpperTriangular, LowerTriangular diff --git a/src/common/pullbacks.jl b/src/common/pullbacks.jl index da4eff952..d0215c343 100644 --- a/src/common/pullbacks.jl +++ b/src/common/pullbacks.jl @@ -11,8 +11,25 @@ function iszerotangent end iszerotangent(::Any) = false iszerotangent(::Nothing) = true -# fallback -_sylvester(A, B, C) = LinearAlgebra.sylvester(A, B, C) +# Solve the Sylvester equation `P * X + X * P = C` for a Hermitian positive semidefinite `P` +# with eigendecomposition `P = U * Diagonal(d) * U'`. +function _sylvester_psd(U, d, C, tol) + Y = U' * C * U + dd = d .+ transpose(d) + Δ = maximum(abs, (abs.(dd ./ 2) .< tol) .* Y; init = zero(real(eltype(Y)))) + Y .*= inv_safe.(dd, tol) + return U * Y * U', Δ +end + +# Remove from `X` its block within the null space of the Hermitian positive semidefinite +# `P = U * Diagonal(d) * U'`, i.e. the eigenvectors with eigenvalues smaller than `tol`. +function _remove_null_block!(X, U, d, tol) + isnull = abs.(d) .< tol + any(isnull) || return X + Y = U' * X * U + Y .*= isnull .& transpose(isnull) + return mul!(X, U, Y * U', -1, 1) +end """ select_indices(r::AbstractRange, ind) diff --git a/src/implementations/polar.jl b/src/implementations/polar.jl index 46550ea80..6baa21377 100644 --- a/src/implementations/polar.jl +++ b/src/implementations/polar.jl @@ -62,8 +62,8 @@ function left_polar!(A::AbstractMatrix, WP, alg::PolarViaSVD) W, P = WP W = mul!(W, U, Vᴴ) if !isempty(P) - S .= sqrt.(S) - SsqrtVᴴ = lmul!(S, Vᴴ) + Ssqrt = sqrt.(diagview(S)) + SsqrtVᴴ = Vᴴ .= Ssqrt .* Vᴴ P = _mul_herm!(P, SsqrtVᴴ') end return (W, P) @@ -74,8 +74,8 @@ function right_polar!(A::AbstractMatrix, PWᴴ, alg::PolarViaSVD) P, Wᴴ = PWᴴ Wᴴ = mul!(Wᴴ, U, Vᴴ) if !isempty(P) - S .= sqrt.(S) - USsqrt = rmul!(U, S) + Ssqrt = reshape(sqrt.(diagview(S)), 1, :) + USsqrt = U .= U .* Ssqrt P = _mul_herm!(P, USsqrt) end return (P, Wᴴ) diff --git a/src/pullbacks/polar.jl b/src/pullbacks/polar.jl index a549321e1..0df21b1a1 100644 --- a/src/pullbacks/polar.jl +++ b/src/pullbacks/polar.jl @@ -1,59 +1,101 @@ """ - left_polar_pullback!(ΔA, A, WP, ΔWP) + left_polar_pullback!( + ΔA, A, WP, ΔWP; + rank_atol::Real = default_pullback_rank_atol(WP[2]), + gauge_atol::Real = default_pullback_gauge_atol(ΔWP...) + ) Adds the pullback from the left polar decomposition of `A` to `ΔA` given the output `WP` and cotangent `ΔWP` of `left_polar(A)`. + +Eigenvalues of `P` smaller than `rank_atol` are treated as zero, in which case `A` is rank +deficient and `W` is not uniquely determined on the null space of `P`. Components of `ΔW` +along this null space are discarded. The block of `ΔP` within the null space, where `P` +is not differentiable, is discarded as well. """ -function left_polar_pullback!(ΔA::AbstractMatrix, A, WP, ΔWP; kwargs...) +function left_polar_pullback!( + ΔA::AbstractMatrix, A, WP, ΔWP; + rank_atol::Real = default_pullback_rank_atol(WP[2]), + gauge_atol::Real = default_pullback_gauge_atol(ΔWP...) + ) # Extract the Polar components W, P = WP # Extract and check the cotangents ΔW, ΔP = ΔWP + D, U = eigh_full(P) + d = diagview(D) if !iszerotangent(ΔP) ΔP = project_hermitian(ΔP) + ΔP = _remove_null_block!(ΔP, U, d, rank_atol) end M = zero(P) !iszerotangent(ΔW) && mul!(M, W', ΔW, 1, 1) !iszerotangent(ΔP) && mul!(M, ΔP, P, -1, 1) - C = _sylvester(P, P, M' - M) + C, Δgauge = _sylvester_psd(U, d, M - M', rank_atol) !iszerotangent(ΔP) && (C .+= ΔP) ΔA = mul!(ΔA, W, C, 1, 1) if !iszerotangent(ΔW) - ΔWP = ΔW / P - WdΔWP = W' * ΔWP - ΔWP = mul!(ΔWP, W, WdΔWP, -1, 1) - ΔA .+= ΔWP + # (1 - W * W') * ΔW * pinv(P) + ΔWU = ΔW * U + WᴴΔWU = W' * ΔWU + ΔWU = mul!(ΔWU, W, WᴴΔWU, -1, 1) + Δgauge = max(Δgauge, maximum(abs, (abs.(transpose(d)) .< rank_atol) .* ΔWU; init = zero(real(eltype(ΔWU))))) + ΔWU .*= transpose(inv_safe.(d, rank_atol)) + ΔA = mul!(ΔA, ΔWU, U', 1, 1) end + Δgauge ≤ gauge_atol || + @warn "`left_polar` cotangents sensitive to gauge choice: (|Δgauge| = $Δgauge)" return ΔA end """ - right_polar_pullback!(ΔA, A, PWᴴ, ΔPWᴴ) + right_polar_pullback!( + ΔA, A, PWᴴ, ΔPWᴴ; + rank_atol::Real = default_pullback_rank_atol(PWᴴ[1]), + gauge_atol::Real = default_pullback_gauge_atol(ΔPWᴴ...) + ) -Adds the pullback from the left polar decomposition of `A` to `ΔA` given the output `PWᴴ` +Adds the pullback from the right polar decomposition of `A` to `ΔA` given the output `PWᴴ` and cotangent `ΔPWᴴ` of `right_polar(A)`. + +Eigenvalues of `P` smaller than `rank_atol` are treated as zero, in which case `A` is rank +deficient and `Wᴴ` is not uniquely determined on the null space of `P`. Components of `ΔWᴴ` +along this null space are discarded. The block of `ΔP` within the null space, where `P` is +not differentiable, is discarded as well. """ -function right_polar_pullback!(ΔA::AbstractMatrix, A, PWᴴ, ΔPWᴴ; kwargs...) +function right_polar_pullback!( + ΔA::AbstractMatrix, A, PWᴴ, ΔPWᴴ; + rank_atol::Real = default_pullback_rank_atol(PWᴴ[1]), + gauge_atol::Real = default_pullback_gauge_atol(ΔPWᴴ...) + ) # Extract the Polar components P, Wᴴ = PWᴴ # Extract and check the cotangents ΔP, ΔWᴴ = ΔPWᴴ + D, U = eigh_full(P) + d = diagview(D) if !iszerotangent(ΔP) ΔP = project_hermitian(ΔP) + ΔP = _remove_null_block!(ΔP, U, d, rank_atol) end M = zero(P) !iszerotangent(ΔWᴴ) && mul!(M, ΔWᴴ, Wᴴ', 1, 1) !iszerotangent(ΔP) && mul!(M, P, ΔP, -1, 1) - C = _sylvester(P, P, M' - M) + C, Δgauge = _sylvester_psd(U, d, M - M', rank_atol) !iszerotangent(ΔP) && (C .+= ΔP) ΔA = mul!(ΔA, C, Wᴴ, 1, 1) if !iszerotangent(ΔWᴴ) - PΔWᴴ = P \ ΔWᴴ - PΔWᴴW = PΔWᴴ * Wᴴ' - PΔWᴴ = mul!(PΔWᴴ, PΔWᴴW, Wᴴ, -1, 1) - ΔA .+= PΔWᴴ + # pinv(P) * ΔWᴴ * (1 - Wᴴ' * Wᴴ) + UᴴΔWᴴ = U' * ΔWᴴ + UᴴΔWᴴW = UᴴΔWᴴ * Wᴴ' + UᴴΔWᴴ = mul!(UᴴΔWᴴ, UᴴΔWᴴW, Wᴴ, -1, 1) + Δgauge = max(Δgauge, maximum(abs, (abs.(d) .< rank_atol) .* UᴴΔWᴴ; init = zero(real(eltype(UᴴΔWᴴ))))) + UᴴΔWᴴ .*= inv_safe.(d, rank_atol) + ΔA = mul!(ΔA, U, UᴴΔWᴴ, 1, 1) end + Δgauge ≤ gauge_atol || + @warn "`right_polar` cotangents sensitive to gauge choice: (|Δgauge| = $Δgauge)" return ΔA end diff --git a/src/pullbacks/svd.jl b/src/pullbacks/svd.jl index 576997b69..2c86e522f 100755 --- a/src/pullbacks/svd.jl +++ b/src/pullbacks/svd.jl @@ -1,5 +1,17 @@ svd_rank(S; rank_atol = default_pullback_rank_atol(S)) = searchsortedlast(S, rank_atol; rev = true) +# Size of the gauge-dependent part of the cotangent `ΔX` of isometric columns `X` that are not +# uniquely determined (singular vectors of zero singular values, or the extra columns of a full +# SVD), assuming that the determined part of `ΔX` has already been removed. Only the antihermitian +# part of `X' * ΔX` (rotations among the columns of `X`) and the component of `ΔX` orthogonal to `X` +# (rotations of the span of `X` into other directions) are gauge dependent. +function _null_gauge_dependence(X, ΔX) + XᴴΔX = X' * ΔX + ΔX⊥ = ΔX - X * XᴴΔX + init = zero(real(eltype(XᴴΔX))) + return max(maximum(abs, project_antihermitian(XᴴΔX); init), maximum(abs, ΔX⊥; init)) +end + function check_and_prepare_svd_cotangents( U, S, Vᴴ, ΔU, ΔSmat, ΔVᴴ, r::Int, ind = Colon(); degeneracy_atol::Real = default_pullback_rank_atol(S), @@ -31,7 +43,19 @@ function check_and_prepare_svd_cotangents( length(indU) == size(ΔU, 2) || throw(DimensionMismatch(lazy"length of selected U columns ($(length(indU))) does not match second dimension of ΔU ($(size(ΔU, 2)))")) if indU == indS ΔU₀ = ΔU[:, J₁] - ΔgaugeU = max(ΔgaugeU, maximum(abs, view(ΔU, :, J₂); init = zero(ΔgaugeU))) + if !isempty(J₂) && is_leading_index(ind₀, r) + # The singular vectors U₂ of the (numerically) zero singular values are not uniquely + # determined, but their overlap with U₁ *is*: U₁' * U̇₂ = -U̇₁' * U₂. + # Fold the corresponding part of ΔU₂ into ΔU₁; only the remainder is gauge dependent. + U₂ = U[:, indU[J₂]] + ΔU₂ = ΔU[:, J₂] + U₁ᴴΔU₂ = U₁' * ΔU₂ + mul!(ΔU₀, U₂, U₁ᴴΔU₂', -1, 1) + mul!(ΔU₂, U₁, U₁ᴴΔU₂, -1, 1) + ΔgaugeU = max(ΔgaugeU, _null_gauge_dependence(U₂, ΔU₂)) + else + ΔgaugeU = max(ΔgaugeU, maximum(abs, view(ΔU, :, J₂); init = zero(ΔgaugeU))) + end elseif full_rank && indU == 1:m ΔU₀ = ΔU[:, ind₀] J₃ = (r + 1):m @@ -40,7 +64,7 @@ function check_and_prepare_svd_cotangents( U₁ᴴΔU₃ = U₁' * ΔU₃ # gauge-invariant part mul!(ΔU₀, U₃, U₁ᴴΔU₃', -1, 1) mul!(ΔU₃, U₁, U₁ᴴΔU₃, -1, 1) - ΔgaugeU = max(ΔgaugeU, maximum(abs, ΔU₃; init = zero(ΔgaugeU))) + ΔgaugeU = max(ΔgaugeU, _null_gauge_dependence(U₃, ΔU₃)) else throw(ArgumentError(lazy"Unexpected selection of U columns: indU = $indU, expected indS = $indS or 1:$m")) end @@ -58,7 +82,17 @@ function check_and_prepare_svd_cotangents( length(indV) == size(ΔVᴴ, 1) || throw(DimensionMismatch(lazy"length of selected Vᴴ rows ($(length(indV))) does not match first dimension of ΔVᴴ ($(size(ΔVᴴ, 1)))")) if indV == indS ΔV₀ᴴ = ΔVᴴ[J₁, :] - ΔgaugeV = max(ΔgaugeV, maximum(abs, view(ΔVᴴ, J₂, :); init = zero(ΔgaugeV))) + if !isempty(J₂) && is_leading_index(ind₀, r) + # As for U: V₁' * V̇₂ = -V̇₁' * V₂ is determined, so fold that part of ΔV₂ into ΔV₁ + V₂ᴴ = Vᴴ[indV[J₂], :] + ΔV₂ᴴ = ΔVᴴ[J₂, :] + V₁ᴴΔV₂ = V₁ᴴ * ΔV₂ᴴ' + mul!(ΔV₀ᴴ, V₁ᴴΔV₂, V₂ᴴ, -1, 1) + mul!(ΔV₂ᴴ, V₁ᴴΔV₂', V₁ᴴ, -1, 1) + ΔgaugeV = max(ΔgaugeV, _null_gauge_dependence(V₂ᴴ', ΔV₂ᴴ')) + else + ΔgaugeV = max(ΔgaugeV, maximum(abs, view(ΔVᴴ, J₂, :); init = zero(ΔgaugeV))) + end elseif full_rank && indV == 1:n ΔV₀ᴴ = ΔVᴴ[ind₀, :] J₃ = (r + 1):n @@ -67,7 +101,7 @@ function check_and_prepare_svd_cotangents( V₁ᴴΔV₃ = V₁ᴴ * (ΔV₃ᴴ)' # gauge-invariant part mul!(ΔV₀ᴴ, V₁ᴴΔV₃, V₃ᴴ, -1, 1) mul!(ΔV₃ᴴ, V₁ᴴΔV₃', V₁ᴴ, -1, 1) - ΔgaugeV = max(ΔgaugeV, maximum(abs, ΔV₃ᴴ; init = zero(ΔgaugeV))) + ΔgaugeV = max(ΔgaugeV, _null_gauge_dependence(V₃ᴴ', ΔV₃ᴴ')) else throw(ArgumentError(lazy"Unexpected selection of Vᴴ rows: indV = $indV, expected indS = $indS or 1:$n")) end @@ -91,7 +125,8 @@ function check_and_prepare_svd_cotangents( ΔS = diagview(ΔSmat) length(indS) == length(ΔS) || throw(DimensionMismatch(lazy"length of selected S values ($(length(indS))) does not match length of ΔS ($(length(ΔS)))")) hUᴴΔAV₁₀[ind₀ .+ r .* (0:(length(ind₀) - 1))] .+= real.(ΔS[J₁]) # diagonal entries - Δgauge = max(Δgauge, maximum(abs, ΔS[J₂]; init = zero(Δgauge))) + # ΔS[J₂] belongs to singular values below `rank_atol`, which are treated as zero. These + # are not differentiable, so their cotangents are discarded. end Δgauge ≤ gauge_atol || @@ -119,6 +154,12 @@ and the argument `ind` is a list of length `p` indicating that these are cotange whereas cotangents with respect to the other rows and columns are zero. If `ind` is not present, `ΔU`, `ΔS` and `ΔVᴴ` are assumed to have the same size as `U`, `S` and `Vᴴ` respectively. +Singular values smaller than `rank_atol` are treated as zero, in which case `A` is rank +deficient. The pullback then corresponds to the derivative along perturbations of `A` that +preserve its rank: cotangents of the zero singular values are discarded, since these are not +differentiable, and so are the components of `ΔU` and `ΔVᴴ` that rotate the corresponding +singular vectors among themselves, since these are not uniquely determined. + A warning will be printed if the cotangents are not gauge-invariant, i.e. if the anti-hermitian part of `U' * ΔU + Vᴴ * ΔVᴴ'`, restricted to rows `i` and columns `j` for which `abs(S[i] - S[j]) < degeneracy_atol`, is not small compared to `gauge_atol`. @@ -303,6 +344,10 @@ magnitude less than `rank_atol` are missing from `S`. For the cotangents, an arb number of singular vectors or singular values can be missing, i.e. for a matrix `A` with size `(m, n)`, `diagview(ΔS)` can have length `pS`. In those cases, additionally `ind` is required to specify which singular vectors and values are present in `ΔS`. + +Singular values smaller than `rank_atol` are treated as zero; their cotangents are discarded, +since these singular values are not differentiable. The result is the derivative along +perturbations of `A` that preserve its rank. """ function svd_vals_pullback!( ΔA, A, USVᴴ, ΔS, ind = Colon(); diff --git a/src/pushforwards/polar.jl b/src/pushforwards/polar.jl index 6238ffa4c..f9ef23db7 100644 --- a/src/pushforwards/polar.jl +++ b/src/pushforwards/polar.jl @@ -1,25 +1,41 @@ -function left_polar_pushforward!(ΔA, A, WP, ΔWP; kwargs...) +function left_polar_pushforward!( + ΔA, A, WP, ΔWP; rank_atol::Real = default_pullback_rank_atol(WP[2]), kwargs... + ) W, P = WP ΔW, ΔP = ΔWP + D, U = eigh_full(P) + d = diagview(D) mul!(ΔP, adjoint(W), ΔA, +1, 0) - K̇ = _sylvester(P, P, adjoint(ΔP) - ΔP) - mul!(ΔW, ΔA, inv(P), +1, 0) + K̇, = _sylvester_psd(U, d, ΔP - adjoint(ΔP), rank_atol) + # ΔA * pinv(P) + ΔAU = ΔA * U + ΔAU .*= transpose(inv_safe.(d, rank_atol)) + mul!(ΔW, ΔAU, adjoint(U), +1, 0) WᴴdAiP = W' * ΔW mul!(ΔW, W, WᴴdAiP, -1, +1) ΔW = mul!(ΔW, W, K̇, +1, +1) ΔP = mul!(ΔP, K̇, P, -1, +1) + ΔP = _remove_null_block!(ΔP, U, d, rank_atol) return (ΔW, ΔP) end -function right_polar_pushforward!(ΔA, A, PWᴴ, ΔPWᴴ; kwargs...) +function right_polar_pushforward!( + ΔA, A, PWᴴ, ΔPWᴴ; rank_atol::Real = default_pullback_rank_atol(PWᴴ[1]), kwargs... + ) P, Wᴴ = PWᴴ ΔP, ΔWᴴ = ΔPWᴴ + D, U = eigh_full(P) + d = diagview(D) mul!(ΔP, ΔA, adjoint(Wᴴ), +1, 0) - K̇ = _sylvester(P, P, adjoint(ΔP) - ΔP) - mul!(ΔWᴴ, inv(P), ΔA, +1, 0) + K̇, = _sylvester_psd(U, d, ΔP - adjoint(ΔP), rank_atol) + # pinv(P) * ΔA + UᴴΔA = U' * ΔA + UᴴΔA .*= inv_safe.(d, rank_atol) + mul!(ΔWᴴ, U, UᴴΔA, +1, 0) iPdAW = ΔWᴴ * Wᴴ' mul!(ΔWᴴ, iPdAW, Wᴴ, -1, +1) ΔWᴴ = mul!(ΔWᴴ, K̇, Wᴴ, +1, +1) ΔP = mul!(ΔP, P, K̇, -1, +1) + ΔP = _remove_null_block!(ΔP, U, d, rank_atol) return (ΔWᴴ, ΔP) end diff --git a/test/testsuite/ad_utils.jl b/test/testsuite/ad_utils.jl index ca556890e..37bf13145 100644 --- a/test/testsuite/ad_utils.jl +++ b/test/testsuite/ad_utils.jl @@ -41,7 +41,7 @@ project_antihermitian_inplace!(A, alg) = project_antihermitian!(A, A, alg) enzyme_fdm(T) = eltype(T) <: Union{Float32, ComplexF32} ? EnzymeTestUtils.FiniteDifferences.central_fdm(5, 1, max_range = 1.0e-2) : EnzymeTestUtils.FiniteDifferences.central_fdm(5, 1) - +const rank_deficient_fdm = EnzymeTestUtils.FiniteDifferences.central_fdm(5, 1, max_range = 1.0e-4) """ eigh_wrapper(f, A, alg) @@ -376,6 +376,83 @@ function ad_right_polar_setup(A) return PWᴴ, ΔPWᴴ end +""" + left_polar_rank_deficient_wrapper(f, L, R, alg) + +Wrapper that calls `W, P = f(L * R, alg)` for a rank-deficient product `L * R` and returns +`W * P` and `P`. Parametrizing the input by its factors restricts FD to rank-preserving directions. +""" +left_polar_rank_deficient_wrapper(f, L, R, alg) = left_polar_gauge_invariant_part(f(L * R, alg)) + +""" + left_polar!_rank_deficient_wrapper(f!, L, R, alg) + +In-place variant of [`left_polar_rank_deficient_wrapper`](@ref). +""" +left_polar!_rank_deficient_wrapper(f!, L, R, alg) = + left_polar_gauge_invariant_part(call_and_zero!(f!, L * R, alg)) + +left_polar_gauge_invariant_part((W, P)) = (W * P, P) + +""" + right_polar_rank_deficient_wrapper(f, L, R, alg) + +Wrapper that calls `P, Wᴴ = f(L * R, alg)` for a rank-deficient product `L * R` and returns +`P` and `P * Wᴴ`. Parametrizing the input by its factors restricts FD to rank-preserving directions. +""" +right_polar_rank_deficient_wrapper(f, L, R, alg) = right_polar_gauge_invariant_part(f(L * R, alg)) + +""" + right_polar!_rank_deficient_wrapper(f!, L, R, alg) + +In-place variant of [`right_polar_rank_deficient_wrapper`](@ref). +""" +right_polar!_rank_deficient_wrapper(f!, L, R, alg) = + right_polar_gauge_invariant_part(call_and_zero!(f!, L * R, alg)) + +right_polar_gauge_invariant_part((P, Wᴴ)) = (P, P * Wᴴ) + +""" + polar_P_wrapper(f, A, alg) + +Wrapper that returns only the positive factor `P` of the polar decomposition `f(A, alg)`. +""" +polar_P_wrapper(f, A, alg) = (F = f(A, alg); f === left_polar ? F[2] : F[1]) + +function rank_deficient_factors(T, (m, n)) + r = div(min(m, n), 2) + return instantiate_matrix(T, (m, r)), instantiate_matrix(T, (r, n)) +end + +""" + svd_null_projector_wrapper(f, L, R, alg) + +Wrapper that calls `U, S, Vᴴ = f(L * R, alg)` for a product `L * R` of rank `r = size(L, 2)` +and returns the orthogonal projectors onto the null spaces, built from the singular vectors +`U₂ = U[:, r+1:end]` and `V₂ᴴ = Vᴴ[r+1:end, :]` of the zero singular values. These singular +vectors are not unique, but the projectors are, provided that the compact SVD fixes the span of +`U₂` (`m ≤ n`) or of `V₂` (`m ≥ n`); only those projectors are returned. Their derivatives +probe the part of the cotangents of `U₂` and `V₂` that is determined by `U₁` and `V₁`. +Parametrizing the input by its factors restricts FD to rank-preserving directions. +""" +svd_null_projector_wrapper(f, L, R, alg) = svd_null_projectors(f(L * R, alg), size(L, 2)) + +""" + svd!_null_projector_wrapper(f!, L, R, alg) + +In-place variant of [`svd_null_projector_wrapper`](@ref). +""" +svd!_null_projector_wrapper(f!, L, R, alg) = + svd_null_projectors(call_and_zero!(f!, L * R, alg), size(L, 2)) + +function svd_null_projectors((U, S, Vᴴ), r) + m, n = size(U, 1), size(Vᴴ, 2) + U₂ = U[:, (r + 1):end] + V₂ᴴ = Vᴴ[(r + 1):end, :] + m == n && return (U₂ * U₂', V₂ᴴ' * V₂ᴴ) + return m > n ? V₂ᴴ' * V₂ᴴ : U₂ * U₂' +end + function ad_left_orth_setup(A) VC = left_orth(A) ΔVC = structured_randn!.(similar.(VC)) diff --git a/test/testsuite/chainrules.jl b/test/testsuite/chainrules.jl index df95e7026..5cd4c261c 100755 --- a/test/testsuite/chainrules.jl +++ b/test/testsuite/chainrules.jl @@ -523,6 +523,13 @@ function test_chainrules_svd( ) @test isequal(ΔUSVᴴ, ΔUSVᴴ_copy) end + @testset "svd_compact rank deficient" begin + L, R = rank_deficient_factors(T, sz) + test_rrule( + config, svd_null_projector_wrapper, svd_compact ⊢ NoTangent(), L, R, alg ⊢ NoTangent(); + atol = atol, rtol = rtol, rrule_f = rrule_via_ad, check_inferred = false + ) + end @testset "svd_full" begin USV, ΔUSVᴴ = ad_svd_full_setup(A) ΔUSVᴴ_copy = deepcopy(ΔUSVᴴ) @@ -691,6 +698,17 @@ function test_chainrules_polar( atol = atol, rtol = rtol, rrule_f = rrule_via_ad, check_inferred = false ) @test isequal(ΔWP, ΔWP_copy) + + Ar = instantiate_rank_deficient_matrix(T, sz) + test_rrule( + config, polar_P_wrapper, left_polar ⊢ NoTangent(), Ar, alg ⊢ NoTangent(); + atol = atol, rtol = rtol, rrule_f = rrule_via_ad, check_inferred = false + ) + L, R = rank_deficient_factors(T, sz) + test_rrule( + config, left_polar_rank_deficient_wrapper, left_polar ⊢ NoTangent(), L, R, alg ⊢ NoTangent(); + atol = atol, rtol = rtol, rrule_f = rrule_via_ad, check_inferred = false + ) end end @testset "right_polar" begin @@ -708,6 +726,17 @@ function test_chainrules_polar( atol = atol, rtol = rtol, rrule_f = rrule_via_ad, check_inferred = false ) @test isequal(ΔPWᴴ, ΔPWᴴ_copy) + + Ar = instantiate_rank_deficient_matrix(T, sz) + test_rrule( + config, polar_P_wrapper, right_polar ⊢ NoTangent(), Ar, alg ⊢ NoTangent(); + atol = atol, rtol = rtol, rrule_f = rrule_via_ad, check_inferred = false + ) + L, R = rank_deficient_factors(T, sz) + test_rrule( + config, right_polar_rank_deficient_wrapper, right_polar ⊢ NoTangent(), L, R, alg ⊢ NoTangent(); + atol = atol, rtol = rtol, rrule_f = rrule_via_ad, check_inferred = false + ) end end end diff --git a/test/testsuite/enzyme/polar.jl b/test/testsuite/enzyme/polar.jl index 21cf54f67..f43230f35 100644 --- a/test/testsuite/enzyme/polar.jl +++ b/test/testsuite/enzyme/polar.jl @@ -25,13 +25,31 @@ function test_enzyme_left_polar( A = instantiate_matrix(T, sz) m, n = size(A) if m >= n - alg = MatrixAlgebraKit.select_algorithm(left_polar, A) - WP, ΔWP = ad_left_polar_setup(A) - test_reverse(left_polar, RT, (A, TA), (alg, Const); atol, rtol) - test_reverse(call_and_zero!, RT, (left_polar!, Const), (A, TA), (alg, Const); atol, rtol) - A = instantiate_matrix(T, sz) - test_forward(left_polar, RT, (A, TA), (alg, Const); atol, rtol) - test_forward(call_and_zero!, RT, (left_polar!, Const), (A, TA), (alg, Const); atol, rtol) + # test both PolarNewton and PolarViaSVD + algs = A isa Diagonal ? (MatrixAlgebraKit.select_algorithm(left_polar, A),) : + (MatrixAlgebraKit.PolarNewton(), MatrixAlgebraKit.PolarViaSVD(MatrixAlgebraKit.default_algorithm(svd_compact!, typeof(A)))) + @testset for alg in algs + A = instantiate_matrix(T, sz) + WP, ΔWP = ad_left_polar_setup(A) + test_reverse(left_polar, RT, (A, TA), (alg, Const); atol, rtol) + test_reverse(call_and_zero!, RT, (left_polar!, Const), (A, TA), (alg, Const); atol, rtol) + A = instantiate_matrix(T, sz) + test_forward(left_polar, RT, (A, TA), (alg, Const); atol, rtol) + test_forward(call_and_zero!, RT, (left_polar!, Const), (A, TA), (alg, Const); atol, rtol) + + A = instantiate_rank_deficient_matrix(T, sz) + test_reverse(polar_P_wrapper, RT, (left_polar, Const), (A, TA), (alg, Const); atol, rtol, fdm = rank_deficient_fdm) + test_forward(polar_P_wrapper, RT, (left_polar, Const), (A, TA), (alg, Const); atol, rtol, fdm = rank_deficient_fdm) + # TODO: Enzyme can't diff through complex BLAS gemm + if eltype(T) <: Real + L, R = rank_deficient_factors(T, sz) + for wrapper in (left_polar_rank_deficient_wrapper, left_polar!_rank_deficient_wrapper) + f = wrapper === left_polar_rank_deficient_wrapper ? left_polar : left_polar! + test_reverse(wrapper, RT, (f, Const), (L, TA), (R, TA), (alg, Const); atol, rtol) + test_forward(wrapper, RT, (f, Const), (L, TA), (R, TA), (alg, Const); atol, rtol) + end + end + end end end end @@ -50,13 +68,31 @@ function test_enzyme_right_polar( A = instantiate_matrix(T, sz) m, n = size(A) if m <= n - alg = MatrixAlgebraKit.select_algorithm(right_polar, A) - PWᴴ, ΔPWᴴ = ad_right_polar_setup(A) - test_reverse(right_polar, RT, (A, TA), (alg, Const); atol, rtol) - test_reverse(call_and_zero!, RT, (right_polar!, Const), (A, TA), (alg, Const); atol, rtol) - A = instantiate_matrix(T, sz) - test_forward(right_polar, RT, (A, TA), (alg, Const); atol, rtol) - test_forward(call_and_zero!, RT, (right_polar!, Const), (A, TA), (alg, Const); atol, rtol) + # test both PolarNewton and PolarViaSVD + algs = A isa Diagonal ? (MatrixAlgebraKit.select_algorithm(right_polar, A),) : + (MatrixAlgebraKit.PolarNewton(), MatrixAlgebraKit.PolarViaSVD(MatrixAlgebraKit.default_algorithm(svd_compact!, typeof(A)))) + @testset for alg in algs + A = instantiate_matrix(T, sz) + PWᴴ, ΔPWᴴ = ad_right_polar_setup(A) + test_reverse(right_polar, RT, (A, TA), (alg, Const); atol, rtol) + test_reverse(call_and_zero!, RT, (right_polar!, Const), (A, TA), (alg, Const); atol, rtol) + A = instantiate_matrix(T, sz) + test_forward(right_polar, RT, (A, TA), (alg, Const); atol, rtol) + test_forward(call_and_zero!, RT, (right_polar!, Const), (A, TA), (alg, Const); atol, rtol) + + A = instantiate_rank_deficient_matrix(T, sz) + test_reverse(polar_P_wrapper, RT, (right_polar, Const), (A, TA), (alg, Const); atol, rtol, fdm = rank_deficient_fdm) + test_forward(polar_P_wrapper, RT, (right_polar, Const), (A, TA), (alg, Const); atol, rtol, fdm = rank_deficient_fdm) + # TODO: Enzyme can't diff through complex BLAS gemm + if eltype(T) <: Real + L, R = rank_deficient_factors(T, sz) + for wrapper in (right_polar_rank_deficient_wrapper, right_polar!_rank_deficient_wrapper) + f = wrapper === right_polar_rank_deficient_wrapper ? right_polar : right_polar! + test_reverse(wrapper, RT, (f, Const), (L, TA), (R, TA), (alg, Const); atol, rtol) + test_forward(wrapper, RT, (f, Const), (L, TA), (R, TA), (alg, Const); atol, rtol) + end + end + end end end end diff --git a/test/testsuite/enzyme/svd.jl b/test/testsuite/enzyme/svd.jl index e3fc4b41e..6973d2f5f 100644 --- a/test/testsuite/enzyme/svd.jl +++ b/test/testsuite/enzyme/svd.jl @@ -2,6 +2,8 @@ function test_enzyme_svd(T::Type, sz; kwargs...) summary_str = testargs_summary(T, sz) return @testset "Enzyme svd $summary_str" begin test_enzyme_svd_compact(T, sz; kwargs...) + # TODO: Enzyme can't diff through complex BLAS gemm + T <: Real && test_enzyme_svd_compact_rank_deficient(T, sz; kwargs...) test_enzyme_svd_full(T, sz; kwargs...) test_enzyme_svd_vals(T, sz; kwargs...) test_enzyme_svd_trunc(T, sz; kwargs...) @@ -29,6 +31,28 @@ function test_enzyme_svd_compact( end end +""" + test_enzyme_svd_compact_rank_deficient(T, sz; rng, atol, rtol) + +Test the Enzyme forward- and reverse-mode AD rule for `svd_compact` and its in-place variant +on a rank-deficient matrix, through the gauge-invariant projectors onto its null spaces +(see [`svd_null_projector_wrapper`](@ref)). +""" +function test_enzyme_svd_compact_rank_deficient( + T, sz; + rng = TestSuite.rng, atol::Real = 0, rtol::Real = precision(T), + fdm = enzyme_fdm(T) + ) + return @testset "svd_compact rank deficient: RT $RT, TA $TA" for RT in (Duplicated,), TA in (Duplicated,) + L, R = rank_deficient_factors(T, sz) + alg = MatrixAlgebraKit.select_algorithm(svd_compact, L * R) + test_reverse(svd_null_projector_wrapper, RT, (svd_compact, Const), (L, TA), (R, TA), (alg, Const); atol, rtol, fdm) + test_reverse(svd!_null_projector_wrapper, RT, (svd_compact!, Const), (L, TA), (R, TA), (alg, Const); atol, rtol, fdm) + test_forward(svd_null_projector_wrapper, RT, (svd_compact, Const), (L, TA), (R, TA), (alg, Const); atol, rtol, fdm) + test_forward(svd!_null_projector_wrapper, RT, (svd_compact!, Const), (L, TA), (R, TA), (alg, Const); atol, rtol, fdm) + end +end + """ test_enzyme_svd_full(T, sz; rng, atol, rtol) diff --git a/test/testsuite/mooncake/polar.jl b/test/testsuite/mooncake/polar.jl index 5170b5d57..fc98e45b4 100644 --- a/test/testsuite/mooncake/polar.jl +++ b/test/testsuite/mooncake/polar.jl @@ -25,18 +25,37 @@ function test_mooncake_left_polar( A = instantiate_matrix(T, sz) m, n = size(A) @assert m >= n - alg = MatrixAlgebraKit.select_algorithm(left_polar, A) - WP, ΔWP = ad_left_polar_setup(A) - output_tangent = Mooncake.primal_to_tangent!!(Mooncake.zero_tangent(WP), ΔWP) + algs = A isa Diagonal ? (MatrixAlgebraKit.select_algorithm(left_polar, A),) : + (MatrixAlgebraKit.PolarNewton(), MatrixAlgebraKit.PolarViaSVD(MatrixAlgebraKit.default_algorithm(svd_compact!, typeof(A)))) + @testset for alg in algs + A = instantiate_matrix(T, sz) + WP, ΔWP = ad_left_polar_setup(A) + output_tangent = Mooncake.primal_to_tangent!!(Mooncake.zero_tangent(WP), ΔWP) - Mooncake.TestUtils.test_rule( - rng, left_polar, A, alg; - output_tangent, atol, rtol - ) - Mooncake.TestUtils.test_rule( - rng, call_and_zero!, left_polar!, A, alg; - output_tangent, atol, rtol, is_primitive = false - ) + Mooncake.TestUtils.test_rule( + rng, left_polar, A, alg; + output_tangent, atol, rtol, is_primitive = !(alg isa MatrixAlgebraKit.PolarViaSVD) + ) + Mooncake.TestUtils.test_rule( + rng, call_and_zero!, left_polar!, A, alg; + output_tangent, atol, rtol, is_primitive = false + ) + + A = instantiate_rank_deficient_matrix(T, (m, n)) + Mooncake.TestUtils.test_rule( + rng, polar_P_wrapper, left_polar, A, alg; + atol, rtol, is_primitive = false + ) + L, R = rank_deficient_factors(T, (m, n)) + Mooncake.TestUtils.test_rule( + rng, left_polar_rank_deficient_wrapper, left_polar, L, R, alg; + atol, rtol, is_primitive = false + ) + Mooncake.TestUtils.test_rule( + rng, left_polar!_rank_deficient_wrapper, left_polar!, L, R, alg; + atol, rtol, is_primitive = false + ) + end end end @@ -54,17 +73,36 @@ function test_mooncake_right_polar( A = instantiate_matrix(T, sz) m, n = size(A) @assert m <= n - alg = MatrixAlgebraKit.select_algorithm(right_polar, A) - PWᴴ, ΔPWᴴ = ad_right_polar_setup(A) - output_tangent = Mooncake.primal_to_tangent!!(Mooncake.zero_tangent(PWᴴ), ΔPWᴴ) + algs = A isa Diagonal ? (MatrixAlgebraKit.select_algorithm(right_polar, A),) : + (MatrixAlgebraKit.PolarNewton(), MatrixAlgebraKit.PolarViaSVD(MatrixAlgebraKit.default_algorithm(svd_compact!, typeof(A)))) + @testset for alg in algs + A = instantiate_matrix(T, sz) + PWᴴ, ΔPWᴴ = ad_right_polar_setup(A) + output_tangent = Mooncake.primal_to_tangent!!(Mooncake.zero_tangent(PWᴴ), ΔPWᴴ) + + Mooncake.TestUtils.test_rule( + rng, right_polar, A, alg; + output_tangent, atol, rtol, is_primitive = !(alg isa MatrixAlgebraKit.PolarViaSVD) + ) + Mooncake.TestUtils.test_rule( + rng, call_and_zero!, right_polar!, A, alg; + output_tangent, atol, rtol, is_primitive = false + ) - Mooncake.TestUtils.test_rule( - rng, right_polar, A, alg; - output_tangent, atol, rtol - ) - Mooncake.TestUtils.test_rule( - rng, call_and_zero!, right_polar!, A, alg; - output_tangent, atol, rtol, is_primitive = false - ) + A = instantiate_rank_deficient_matrix(T, (m, n)) + Mooncake.TestUtils.test_rule( + rng, polar_P_wrapper, right_polar, A, alg; + atol, rtol, is_primitive = false + ) + L, R = rank_deficient_factors(T, (m, n)) + Mooncake.TestUtils.test_rule( + rng, right_polar_rank_deficient_wrapper, right_polar, L, R, alg; + atol, rtol, is_primitive = false + ) + Mooncake.TestUtils.test_rule( + rng, right_polar!_rank_deficient_wrapper, right_polar!, L, R, alg; + atol, rtol, is_primitive = false + ) + end end end diff --git a/test/testsuite/mooncake/svd.jl b/test/testsuite/mooncake/svd.jl index f13faa874..7f88e2cb8 100644 --- a/test/testsuite/mooncake/svd.jl +++ b/test/testsuite/mooncake/svd.jl @@ -7,6 +7,7 @@ function test_mooncake_svd(T::Type, sz; kwargs...) summary_str = testargs_summary(T, sz) return @testset "Mooncake svd $summary_str" begin test_mooncake_svd_compact(T, sz; kwargs...) + T <: Number && test_mooncake_svd_compact_rank_deficient(T, sz; kwargs...) test_mooncake_svd_full(T, sz; kwargs...) test_mooncake_svd_vals(T, sz; kwargs...) test_mooncake_svd_trunc(T, sz; kwargs...) @@ -39,6 +40,31 @@ function test_mooncake_svd_compact( end end +""" + test_mooncake_svd_compact_rank_deficient(T, sz; rng, atol, rtol) + +Test the Mooncake forward- and reverse-mode AD rule for `svd_compact` and its in-place variant +on a rank-deficient matrix, through the gauge-invariant projectors onto its null spaces +(see [`svd_null_projector_wrapper`](@ref)). +""" +function test_mooncake_svd_compact_rank_deficient( + T, sz; + rng = TestSuite.rng, atol::Real = 0, rtol::Real = precision(T) + ) + return @testset "svd_compact rank deficient" begin + L, R = rank_deficient_factors(T, sz) + alg = MatrixAlgebraKit.select_algorithm(svd_compact, L * R) + Mooncake.TestUtils.test_rule( + rng, svd_null_projector_wrapper, svd_compact, L, R, alg; + atol, rtol, is_primitive = false + ) + Mooncake.TestUtils.test_rule( + rng, svd!_null_projector_wrapper, svd_compact!, L, R, alg; + atol, rtol, is_primitive = false + ) + end +end + """ test_mooncake_svd_full(T, sz; rng, atol, rtol)