Skip to content

Commit c3cf149

Browse files
authored
Add forward rules for QR/LQ
Forward rules for QR/LQ
1 parent 38b037e commit c3cf149

13 files changed

Lines changed: 464 additions & 45 deletions

File tree

‎Project.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,5 @@ GenericLinearAlgebra = "0.3.19, 0.4"
3737
GenericSchur = "0.5.6"
3838
LinearAlgebra = "1"
3939
PrecompileTools = "1"
40-
Mooncake = "0.5.27"
40+
Mooncake = "0.5.61"
4141
julia = "1.10"

‎ext/MatrixAlgebraKitEnzymeExt/MatrixAlgebraKitEnzymeExt.jl‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ using MatrixAlgebraKit
44
using MatrixAlgebraKit: copy_input, initialize_output, zero!, has_equal_storage
55
using MatrixAlgebraKit: diagview, inv_safe, truncate
66
using MatrixAlgebraKit: qr_pullback!, lq_pullback!
7+
using MatrixAlgebraKit: qr_pushforward!, lq_pushforward!
78
using MatrixAlgebraKit: qr_null_pullback!, lq_null_pullback!
9+
using MatrixAlgebraKit: qr_null_pushforward!, lq_null_pushforward!
810
using MatrixAlgebraKit: eig_pullback!, eigh_pullback!, eig_vals_pullback!, eigh_vals_pullback!
911
using MatrixAlgebraKit: eig_pushforward!, eigh_pushforward!, eig_vals_pushforward!, eigh_vals_pushforward!
1012
using MatrixAlgebraKit: svd_pullback!, svd_vals_pullback!
@@ -121,6 +123,10 @@ for (f, pf) in (
121123
(:left_polar!, :left_polar_pushforward!),
122124
(:eigh_full!, :eigh_pushforward!),
123125
(:eig_full!, :eig_pushforward!),
126+
(:qr_full!, :qr_pushforward!),
127+
(:lq_full!, :lq_pushforward!),
128+
(:qr_compact!, :qr_pushforward!),
129+
(:lq_compact!, :lq_pushforward!),
124130
)
125131
@eval begin
126132
function EnzymeRules.forward(
@@ -129,7 +135,7 @@ for (f, pf) in (
129135
::Type{RT},
130136
A::Annotation,
131137
arg::Annotation,
132-
alg::Const{<:MatrixAlgebraKit.AbstractAlgorithm},
138+
alg::Annotation{<:MatrixAlgebraKit.AbstractAlgorithm},
133139
) where {RT}
134140
A_is_arg1 = !isa(A, Const) && has_equal_storage(A.val, arg.val[1])
135141
A_is_arg2 = !isa(A, Const) && has_equal_storage(A.val, arg.val[2])
@@ -152,9 +158,9 @@ for (f, pf) in (
152158
end
153159
end
154160

155-
for (f, pb) in (
156-
(qr_null!, qr_null_pullback!),
157-
(lq_null!, lq_null_pullback!),
161+
for (f, pb, pf) in (
162+
(qr_null!, qr_null_pullback!, qr_null_pushforward!),
163+
(lq_null!, lq_null_pullback!, lq_null_pushforward!),
158164
)
159165
@eval begin
160166
function EnzymeRules.augmented_primal(
@@ -203,6 +209,32 @@ for (f, pb) in (
203209
!isa(arg, Const) && make_zero!(arg.dval)
204210
return (nothing, nothing, nothing)
205211
end
212+
function EnzymeRules.forward(
213+
config::EnzymeRules.FwdConfigWidth{1},
214+
func::Const{typeof($f)},
215+
::Type{RT},
216+
A::Annotation,
217+
arg::Annotation,
218+
alg::Annotation{<:MatrixAlgebraKit.AbstractAlgorithm},
219+
) where {RT}
220+
# here, A IS directly used in the pushforward, and overwritten
221+
# in the primal call, so we MUST copy its value
222+
Ac = copy(A.val)
223+
$f(A.val, arg.val, alg.val)
224+
if !isa(A, Const) && !isa(arg, Const)
225+
$pf(A.dval, Ac, arg.val, arg.dval)
226+
end
227+
!isa(A, Const) && make_zero!(A.dval)
228+
if EnzymeRules.needs_primal(config) && EnzymeRules.needs_shadow(config)
229+
return arg
230+
elseif EnzymeRules.needs_primal(config)
231+
return arg.val
232+
elseif EnzymeRules.needs_shadow(config)
233+
return arg.dval
234+
else
235+
return nothing
236+
end
237+
end
206238
end
207239
end
208240

‎ext/MatrixAlgebraKitMooncakeExt/MatrixAlgebraKitMooncakeExt.jl‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ using MatrixAlgebraKit
66
using MatrixAlgebraKit: inv_safe, diagview, copy_input, initialize_output, zero!, has_equal_storage
77
using MatrixAlgebraKit: qr_pullback!, lq_pullback!
88
using MatrixAlgebraKit: qr_null_pullback!, lq_null_pullback!
9+
using MatrixAlgebraKit: qr_pushforward!, lq_pushforward!
10+
using MatrixAlgebraKit: qr_null_pushforward!, lq_null_pushforward!
911
using MatrixAlgebraKit: eig_pullback!, eigh_pullback!, eig_vals_pullback!
1012
using MatrixAlgebraKit: eig_pushforward!, eig_vals_pushforward!
1113
using MatrixAlgebraKit: eigh_pushforward!, eigh_vals_pushforward!
@@ -112,6 +114,10 @@ end
112114
for (f!, f, pf) in (
113115
(:left_polar!, :left_polar, :left_polar_pushforward!),
114116
(:right_polar!, :right_polar, :right_polar_pushforward!),
117+
(:qr_full!, :qr_full, :qr_pushforward!),
118+
(:qr_compact!, :qr_compact, :qr_pushforward!),
119+
(:lq_full!, :lq_full, :lq_pushforward!),
120+
(:lq_compact!, :lq_compact, :lq_pushforward!),
115121
(:eig_full!, :eig_full, :eig_pushforward!),
116122
(:eigh_full!, :eigh_full, :eigh_pushforward!),
117123
)
@@ -180,6 +186,34 @@ for (f!, f, pb, adj) in (
180186
end
181187
end
182188

189+
for (f!, f, pf) in (
190+
(:qr_null!, :qr_null, :qr_null_pushforward!),
191+
(:lq_null!, :lq_null, :lq_null_pushforward!),
192+
)
193+
@eval begin
194+
@is_primitive Mooncake.DefaultCtx Mooncake.ForwardMode Tuple{typeof($f!), Any, Any, MatrixAlgebraKit.AbstractAlgorithm}
195+
function Mooncake.frule!!(f_df::Dual{typeof($f!)}, A_dA::Dual, arg_darg::Dual, alg_dalg::Dual{<:MatrixAlgebraKit.AbstractAlgorithm})
196+
A, dA = arrayify(A_dA)
197+
arg, darg = arrayify(arg_darg)
198+
# the pushforward needs the original A, which is destroyed by $f!
199+
Ac = copy(A)
200+
$f!(A, arg, Mooncake.primal(alg_dalg))
201+
$pf(dA, Ac, arg, darg)
202+
return arg_darg
203+
end
204+
@is_primitive Mooncake.DefaultCtx Mooncake.ForwardMode Tuple{typeof($f), Any, MatrixAlgebraKit.AbstractAlgorithm}
205+
function Mooncake.frule!!(f_df::Dual{typeof($f)}, A_dA::Dual, alg_dalg::Dual{<:MatrixAlgebraKit.AbstractAlgorithm})
206+
A, dA = arrayify(A_dA)
207+
output = $f(A, Mooncake.primal(alg_dalg))
208+
doutput = Mooncake.zero_tangent(output)
209+
output_dual = Dual(output, doutput)
210+
arg, darg = arrayify(output_dual)
211+
$pf(dA, A, arg, darg)
212+
return output_dual
213+
end
214+
end
215+
end
216+
183217
for (f!, f, f_full, f_full!, pb, pf, adj) in (
184218
(:eig_vals!, :eig_vals, :eig_full, :eig_full!, :eig_vals_pullback!, :eig_vals_pushforward!, :eig_vals_adjoint),
185219
(:eigh_vals!, :eigh_vals, :eigh_full, :eigh_full!, :eigh_vals_pullback!, :eigh_vals_pushforward!, :eigh_vals_adjoint),

‎src/MatrixAlgebraKit.jl‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,8 @@ include("pushforwards/polar.jl")
142142
include("pushforwards/eig.jl")
143143
include("pushforwards/eigh.jl")
144144
include("pushforwards/svd.jl")
145+
include("pushforwards/qr.jl")
146+
include("pushforwards/lq.jl")
145147

146148
include("precompile.jl")
147149

‎src/pushforwards/lq.jl‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""
2+
lq_pushforward!(
3+
ΔA, A, LQ, ΔLQ;
4+
rank_atol::Real = default_pullback_rank_atol(LQ[1])
5+
)
6+
7+
Compute the pushforward `ΔLQ` of the LQ decomposition `LQ` of `lq_compact(A;
8+
positive = true)` or `lq_full(A; positive = true)` given the tangent `ΔA` of `A`.
9+
10+
If the original matrix `A` is rank-deficient (rank `r < min(size(A)...)`), only the first `r`
11+
rows of `Q` and the first `r` columns of `L` are differentiable, and the tangents of the
12+
remaining rows of `Q` and columns of `L` are set to zero. Similarly, for `lq_full` the extra
13+
rows of `Q` are only determined up to a unitary rotation, and only their gauge-invariant
14+
tangent component along the first `r` rows of `Q` is computed.
15+
16+
See also [`qr_pushforward!`](@ref).
17+
"""
18+
function lq_pushforward!(
19+
ΔA, A, LQ, ΔLQ;
20+
rank_atol::Real = default_pullback_rank_atol(LQ[1]), kwargs...
21+
)
22+
L, Q = LQ
23+
ΔL, ΔQ = ΔLQ
24+
m = size(L, 1)
25+
n = size(Q, 2)
26+
minmn = min(m, n)
27+
p = lq_rank(L; rank_atol)
28+
(m, n) == size(ΔA) || throw(DimensionMismatch("size of ΔA ($(size(ΔA))) does not match size of L*Q ($m, $n)"))
29+
30+
Q₁ = view(Q, 1:p, :)
31+
# Julia 1.13 `ldiv!` checks `istriu` on the parent, which
32+
# falls back to scalar indexing for a view of a GPU array
33+
L₁₁ = LowerTriangular(L[1:p, 1:p])
34+
L₂₁ = view(L, (p + 1):m, 1:p)
35+
36+
ΔA₁ = view(ΔA, 1:p, :)
37+
ΔA₂ = view(ΔA, (p + 1):m, :)
38+
39+
# compute everything from ΔA before writing to ΔL and ΔQ, which may alias it
40+
# (e.g. `lq_compact!` of a `Diagonal` returns `Q === A`)
41+
# TODO rework this into two versions, one for `Q === A` and one for
42+
# `Q !== A`, to minimize allocations
43+
ΔQ₁ = L₁₁ \ ΔA₁
44+
ΔQ₁Q₁ᴴ = ΔQ₁ * Q₁'
45+
M = ΔQ₁Q₁ᴴ + ΔQ₁Q₁ᴴ'
46+
diagview(M) ./= 2
47+
view(M, uppertriangularind(M)) .= zero(eltype(M))
48+
ΔL₁₁ = L₁₁ * M
49+
ΔQ₁ = mul!(ΔQ₁, M, Q₁, -1, 1)
50+
ΔL₂₁ = ΔA₂ * Q₁'
51+
ΔL₂₁ = mul!(ΔL₂₁, L₂₁, ΔQ₁ * Q₁', -1, 1)
52+
53+
zero!(ΔL)
54+
zero!(ΔQ)
55+
view(ΔQ, 1:p, :) .= ΔQ₁
56+
view(ΔL, 1:p, 1:p) .= ΔL₁₁
57+
view(ΔL, (p + 1):m, 1:p) .= ΔL₂₁
58+
if p == minmn && size(Q, 1) > minmn
59+
Q₃ = view(Q, (minmn + 1):size(Q, 1), :)
60+
ΔQ₃ = view(ΔQ, (minmn + 1):size(Q, 1), :)
61+
mul!(ΔQ₃, Q₃ * ΔQ₁', Q₁, -1, 0)
62+
end
63+
return ΔL, ΔQ
64+
end
65+
66+
"""
67+
lq_null_pushforward!(ΔA, A, Nᴴ, ΔNᴴ; kwargs...)
68+
69+
Compute the pushforward `ΔNᴴ` of the left nullspace basis `Nᴴ` of `lq_null(A)`
70+
given the tangent `ΔA` of `A`.
71+
72+
See also [`lq_pushforward!`](@ref).
73+
"""
74+
function lq_null_pushforward!(ΔA, A, Nᴴ, ΔNᴴ; kwargs...)
75+
if size(Nᴴ, 1) == 0
76+
zero!(ΔNᴴ)
77+
return ΔNᴴ
78+
end
79+
L, Q = lq_compact(A; positive = true)
80+
ΔQNᴴ = ldiv!(LowerTriangular(L), ΔA * Nᴴ')
81+
return mul!(ΔNᴴ, ΔQNᴴ', Q, -1, 0)
82+
end

‎src/pushforwards/qr.jl‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""
2+
qr_pushforward!(
3+
ΔA, A, QR, ΔQR;
4+
rank_atol::Real = default_pullback_rank_atol(QR[2])
5+
)
6+
7+
Computes the pushforward `ΔQR` of the QR decomposition `QR` of `qr_compact(A;
8+
positive = true)` or `qr_full(A; positive = true)` given the tangent `ΔA` of `A`.
9+
10+
If the original matrix `A` is rank-deficient (rank `r < min(size(A)...)`), only the first `r`
11+
columns of `Q` and the first `r` rows of `R` are differentiable, and the tangents of the
12+
remaining columns of `Q` and rows of `R` are set to zero. Similarly, for `qr_full` the extra
13+
columns of `Q` are only determined up to a unitary rotation, and only their gauge-invariant
14+
tangent component along the first `r` columns of `Q` is computed.
15+
"""
16+
function qr_pushforward!(
17+
ΔA, A, QR, ΔQR;
18+
rank_atol::Real = default_pullback_rank_atol(QR[2]), kwargs...
19+
)
20+
Q, R = QR
21+
ΔQ, ΔR = ΔQR
22+
m = size(Q, 1)
23+
n = size(R, 2)
24+
minmn = min(m, n)
25+
p = qr_rank(R; rank_atol)
26+
(m, n) == size(ΔA) || throw(DimensionMismatch("size of ΔA ($(size(ΔA))) does not match size of Q*R ($m, $n)"))
27+
28+
# TODO rework this into two versions, one for `Q === A` and one for
29+
# `Q !== A`, to minimize allocations
30+
Q₁ = view(Q, :, 1:p)
31+
R₁₁ = UpperTriangular(view(R, 1:p, 1:p))
32+
R₁₂ = view(R, 1:p, (p + 1):n)
33+
34+
ΔA₁ = view(ΔA, :, 1:p)
35+
ΔA₂ = view(ΔA, :, (p + 1):n)
36+
37+
ΔQ₁ = ΔA₁ / R₁₁
38+
Q₁ᴴΔQ₁ = Q₁' * ΔQ₁
39+
M = Q₁ᴴΔQ₁ + Q₁ᴴΔQ₁'
40+
diagview(M) ./= 2
41+
view(M, lowertriangularind(M)) .= zero(eltype(M))
42+
ΔR₁₁ = M * R₁₁
43+
ΔQ₁ = mul!(ΔQ₁, Q₁, M, -1, 1)
44+
ΔR₁₂ = Q₁' * ΔA₂
45+
ΔR₁₂ = mul!(ΔR₁₂, Q₁' * ΔQ₁, R₁₂, -1, 1)
46+
47+
zero!(ΔQ)
48+
zero!(ΔR)
49+
view(ΔQ, :, 1:p) .= ΔQ₁
50+
view(ΔR, 1:p, 1:p) .= ΔR₁₁
51+
view(ΔR, 1:p, (p + 1):n) .= ΔR₁₂
52+
if p == minmn && size(Q, 2) > minmn
53+
# extra columns in the case of qr_full, orthogonality to Q₁ fixes their component along Q₁
54+
Q₃ = view(Q, :, (minmn + 1):size(Q, 2))
55+
ΔQ₃ = view(ΔQ, :, (minmn + 1):size(Q, 2))
56+
mul!(ΔQ₃, Q₁, ΔQ₁' * Q₃, -1, 0)
57+
end
58+
return ΔQ, ΔR
59+
end
60+
61+
"""
62+
qr_null_pushforward!(ΔA, A, N, ΔN; kwargs...)
63+
64+
Compute the pushforward `ΔN` of the nullspace basis `N` of `qr_null(A)` given the
65+
tangent `ΔA` of `A`.
66+
67+
See also [`qr_pushforward!`](@ref).
68+
"""
69+
function qr_null_pushforward!(ΔA, A, N, ΔN; kwargs...)
70+
if size(N, 2) == 0
71+
zero!(ΔN)
72+
return ΔN
73+
end
74+
Q, R = qr_compact(A; positive = true)
75+
NᴴΔQ = rdiv!(N' * ΔA, UpperTriangular(R))
76+
return mul!(ΔN, Q, NᴴΔQ', -1, 0)
77+
end

‎test/testsuite/ad_utils.jl‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,84 @@ test in-place Hermitian eigendecomposition rules via Mooncake's non-primitive AD
5959
"""
6060
eigh!_wrapper(f!, A, alg) = (F = f!(project_hermitian!(A), alg); MatrixAlgebraKit.zero!(A); F)
6161

62+
"""
63+
qr_gauge_invariant_wrapper(f, A, alg, r)
64+
65+
Wrapper that calls `Q, R = f(A, alg)` and returns only the parts of the decomposition that
66+
are differentiable functions of `A` if `A` has rank `r`: the first `r` columns of `Q`, the
67+
first `r` rows of `R`, and the projector onto the extra columns of `Q` (for `qr_full`).
68+
Used to test forward-mode QR rules with finite differences, which cannot be restricted to
69+
the gauge-invariant subspace through an `output_tangent`.
70+
"""
71+
qr_gauge_invariant_wrapper(f, A, alg, r) = qr_gauge_invariant_part(f(A, alg), r)
72+
73+
"""
74+
qr!_gauge_invariant_wrapper(f!, A, alg, r)
75+
76+
In-place variant of [`qr_gauge_invariant_wrapper`](@ref), which zeros `A` after calling `f!`.
77+
"""
78+
qr!_gauge_invariant_wrapper(f!, A, alg, r) = qr_gauge_invariant_part(call_and_zero!(f!, A, alg), r)
79+
80+
function qr_gauge_invariant_part((Q, R), r)
81+
minmn = min(size(Q, 1), size(R, 2))
82+
Q₃ = Q[:, (minmn + 1):end]
83+
return Q[:, 1:r], R[1:r, :], Q₃ * Q₃'
84+
end
85+
86+
"""
87+
qr_null_gauge_invariant_wrapper(f, A, alg)
88+
89+
Wrapper that calls `N = f(A, alg)` and returns the projector `N * N'` onto the nullspace,
90+
which, unlike `N` itself, is a differentiable function of `A`.
91+
"""
92+
qr_null_gauge_invariant_wrapper(f, A, alg) = (N = f(A, alg); N * N')
93+
94+
"""
95+
qr_null!_gauge_invariant_wrapper(f!, A, alg)
96+
97+
In-place variant of [`qr_null_gauge_invariant_wrapper`](@ref), which zeros `A` after calling `f!`.
98+
"""
99+
qr_null!_gauge_invariant_wrapper(f!, A, alg) = (N = call_and_zero!(f!, A, alg); N * N')
100+
101+
"""
102+
lq_gauge_invariant_wrapper(f, A, alg, r)
103+
104+
Wrapper that calls `L, Q = f(A, alg)` and returns only the parts of the decomposition that
105+
are differentiable functions of `A` if `A` has rank `r`: the first `r` columns of `L`, the
106+
first `r` rows of `Q`, and the projector onto the extra rows of `Q` (for `lq_full`).
107+
Used to test forward-mode LQ rules with finite differences, which cannot be restricted to
108+
the gauge-invariant subspace through an `output_tangent`.
109+
"""
110+
lq_gauge_invariant_wrapper(f, A, alg, r) = lq_gauge_invariant_part(f(A, alg), r)
111+
112+
"""
113+
lq!_gauge_invariant_wrapper(f!, A, alg, r)
114+
115+
In-place variant of [`lq_gauge_invariant_wrapper`](@ref), which zeros `A` after calling `f!`.
116+
"""
117+
lq!_gauge_invariant_wrapper(f!, A, alg, r) = lq_gauge_invariant_part(call_and_zero!(f!, A, alg), r)
118+
119+
function lq_gauge_invariant_part((L, Q), r)
120+
minmn = min(size(L, 1), size(Q, 2))
121+
Q₃ = Q[(minmn + 1):end, :]
122+
return L[:, 1:r], Q[1:r, :], Q₃' * Q₃
123+
end
124+
125+
"""
126+
lq_null_gauge_invariant_wrapper(f, A, alg)
127+
128+
Wrapper that calls `Nᴴ = f(A, alg)` and returns the projector `Nᴴ' * Nᴴ` onto the nullspace,
129+
which, unlike `Nᴴ` itself, is a differentiable function of `A`.
130+
"""
131+
lq_null_gauge_invariant_wrapper(f, A, alg) = (Nᴴ = f(A, alg); Nᴴ' * Nᴴ)
132+
133+
"""
134+
lq_null!_gauge_invariant_wrapper(f!, A, alg)
135+
136+
In-place variant of [`lq_null_gauge_invariant_wrapper`](@ref), which zeros `A` after calling `f!`.
137+
"""
138+
lq_null!_gauge_invariant_wrapper(f!, A, alg) = (Nᴴ = call_and_zero!(f!, A, alg); Nᴴ' * Nᴴ)
139+
62140
function stabilize_eigvals!(D::AbstractVector)
63141
absD = collect(abs.(D))
64142
p = invperm(sortperm(collect(absD))) # rank of abs(D)

0 commit comments

Comments
 (0)