Skip to content
Open
7 changes: 1 addition & 6 deletions ext/MatrixAlgebraKitAMDGPUExt/MatrixAlgebraKitAMDGPUExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
9 changes: 1 addition & 8 deletions ext/MatrixAlgebraKitCUDAExt/MatrixAlgebraKitCUDAExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
105 changes: 97 additions & 8 deletions ext/MatrixAlgebraKitEnzymeExt/MatrixAlgebraKitEnzymeExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,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(
Expand Down Expand Up @@ -119,9 +117,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!),
Expand Down Expand Up @@ -251,10 +343,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
Expand Down
93 changes: 89 additions & 4 deletions ext/MatrixAlgebraKitMooncakeExt/MatrixAlgebraKitMooncakeExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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!),
Expand Down
2 changes: 1 addition & 1 deletion src/MatrixAlgebraKit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 19 additions & 2 deletions src/common/pullbacks.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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', Δ
Comment on lines +17 to +21

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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', Δ
CU = C * U
Y = U' * CU
dd = d .+ transpose(d)
Δ = maximum(abs, (abs.(dd ./ 2) .< tol) .* Y; init = zero(real(eltype(Y))))
Y .*= inv_safe.(dd, tol)
UY = mul!(CU, U, Y)
UYUd = mul!(Y, Y, U')
return UYUd, Δ

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)
Comment on lines +27 to +31

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
isnull = abs.(d) .< tol
any(isnull) || return X
Y = U' * X * U
Y .*= isnull .& transpose(isnull)
return mul!(X, U, Y * U', -1, 1)
isnull = abs.(d) .< tol
any(isnull) || return X
XU = X * U
Y = U' * XU
Y .*= isnull .& transpose(isnull)
return mul!(X, U, mul!(XU, Y, U'), -1, 1)

An alternative would also be to directly only keep the complement, which is possible with one less allocation, if we are happy with temporarily destroying X halfway through

Suggested change
isnull = abs.(d) .< tol
any(isnull) || return X
Y = U' * X * U
Y .*= isnull .& transpose(isnull)
return mul!(X, U, Y * U', -1, 1)
isnull = abs.(d) .< tol
any(isnull) || return X
XU = X * U
Y = mul!(X, U', XU) # same memory as `X`
Y .*= 1 .- (isnull .& transpose(isnull))
return mul!(X, mul!(XU, U, Y), U')

end

"""
select_indices(r::AbstractRange, ind)
Expand Down
8 changes: 4 additions & 4 deletions src/implementations/polar.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How did this ever work before?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I choose not to question it

SsqrtVᴴ = lmul!(S, Vᴴ)
Ssqrt = sqrt.(diagview(S))
SsqrtVᴴ = Vᴴ .= Ssqrt .* Vᴴ
P = _mul_herm!(P, SsqrtVᴴ')
end
return (W, P)
Expand All @@ -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, :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if that would also work:

Suggested change
Ssqrt = reshape(sqrt.(diagview(S)), 1, :)
Ssqrt = transpose(sqrt.(diagview(S)))

USsqrt = U .= U .* Ssqrt
P = _mul_herm!(P, USsqrt)
end
return (P, Wᴴ)
Expand Down
Loading
Loading