Skip to content

Commit 2b0fa61

Browse files
lkdvosclaude
andauthored
Extract R before constructing Q in Householder QR/LQ (#267)
* Extract R before constructing Q in Householder QR/LQ cuSOLVER's `ormqr` needs a workspace of ~2*m*n elements whose size can only be queried through a 32-bit integer, so it becomes unusable past m ~ 35000. `orgqr` needs no workspace and is faster, but generates Q in the array holding the reflectors, which the old order (construct Q, then copy R out of the packed A) could not combine with returning R. Extracting R/L first lifts the restrictions on an inplace Q (`Q === A`): it now combines with computing R/L and with `positive = true`. The blocked path keeps constructing Q first, as R doubles as workspace for T there. The CUSOLVER driver now always constructs Q with `ungqr!`. Also fixes LQ gauge fixing running with `positive = false` when L is not computed, and makes the Native and GLA drivers reject `Q === A` instead of silently returning garbage. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Drop the cuSOLVER workspace queries They are no longer used now that the CUSOLVER driver always constructs Q with `ungqr!`. Inline the ungqr!-based Q construction into `_qr_buildQ!`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * code review --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 2bf6038 commit 2b0fa61

10 files changed

Lines changed: 208 additions & 28 deletions

File tree

‎docs/src/changelog.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,21 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
2424

2525
### Changed
2626

27+
- `qr_compact!`, `qr_full!`, `lq_compact!` and `lq_full!` now extract `R` (or `L`) before
28+
constructing `Q`, so that an inplace `Q` (supplying `A` itself as output for `Q`) can be combined
29+
with computing `R` (or `L`) and with `positive = true`.
30+
- The CUSOLVER driver constructs `Q` with `ungqr!` instead of `unmqr!`, which is both faster and
31+
avoids the large workspace of `ormqr`, whose 32-bit size query fails altogether for large
32+
matrices.
33+
2734
### Deprecated
2835

2936
### Removed
3037

3138
### Fixed
3239

40+
- LQ decompositions no longer gauge fix `Q` when `positive = false` and `L` is not computed.
41+
3342
### Performance
3443

3544
## [0.6.9](https://github.com/QuantumKitHub/MatrixAlgebraKit.jl/compare/v0.6.8...v0.6.9) - 2026-07-10

‎ext/MatrixAlgebraKitCUDAExt/MatrixAlgebraKitCUDAExt.jl‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ for f in (:geqrf!, :ungqr!, :unmqr!)
3333
@eval $f(::CUSOLVER, args...) = YACUSOLVER.$f(args...)
3434
end
3535

36+
MatrixAlgebraKit.prefers_ungqr(::CUSOLVER) = true
37+
3638
MatrixAlgebraKit.supports_svd_full(::CUSOLVER, f::Symbol) = f in (:qr_iteration, :jacobi, :svd_polar)
3739

3840
function gesvd!(::CUSOLVER, A::StridedCuMatrix, S::StridedCuVector, U::StridedCuMatrix, Vᴴ::StridedCuMatrix; kwargs...)

‎ext/MatrixAlgebraKitGenericLinearAlgebraExt.jl‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ function qr_householder!(
6161
throw(ArgumentError(lazy"$driver does not provide a blocked QR decomposition"))
6262
pivoted &&
6363
throw(ArgumentError(lazy"$driver does not provide a pivoted QR decomposition"))
64+
Q === A &&
65+
throw(ArgumentError(lazy"$driver does not provide an inplace Q"))
6466

6567
m, n = size(A)
6668
minmn = min(m, n)

‎src/implementations/lq.jl‎

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,13 @@ for f in (:gelqt!, :gemlqt!, :gelqf!, :unglq!, :unmlq!)
123123
end
124124
end
125125

126+
# copy L out of the packed factorization, leaving the reflectors in A intact
127+
function _lq_copyL!(L::AbstractMatrix, A::AbstractMatrix)
128+
copyto!(L, view(A, axes(L)...))
129+
lowertriangular!(L)
130+
return L
131+
end
132+
126133
@inline lq_householder!(A, L, Q; driver::Driver = DefaultDriver(), kwargs...) =
127134
lq_householder!(driver, A, L, Q; kwargs...)
128135
lq_householder!(::DefaultDriver, A, L, Q; kwargs...) =
@@ -144,34 +151,39 @@ function lq_householder!(
144151
computeL = length(L) > 0
145152
inplaceQ = Q === A
146153

147-
(inplaceQ && (computeL || positive || blocksize > 1 || n < m)) &&
148-
throw(ArgumentError("inplace Q only supported if matrix is wide (`m <= n`), L is not required, and using the unblocked algorithm (`blocksize = 1`) with `positive = false`"))
154+
if inplaceQ
155+
# unglq! builds Q in the space of A, so L has to be extracted first and cannot alias A
156+
(blocksize == 1 && n >= m) ||
157+
throw(ArgumentError(lazy"in-place Q is only supported if matrix is wide (`$m ≤ $n`) and using the unblocked algorithm (`blocksize = $blocksize`)"))
158+
(computeL && Base.mightalias(L, A)) &&
159+
throw(ArgumentError("in-place Q is only supported if L does not share memory with A"))
160+
end
161+
149162
if blocksize > 1
163+
# L doubles as workspace for T, so Q is constructed before L is extracted
150164
mb = min(minmn, blocksize)
151165
if computeL # first use L as space for T
152166
A, T = gelqt!(driver, A, view(L, 1:mb, 1:minmn))
153167
else
154168
A, T = gelqt!(driver, A, similar(A, mb, minmn))
155169
end
156170
Q = gemlqt!(driver, 'R', 'N', A, T, one!(Q))
171+
computeL && _lq_copyL!(L, A)
172+
positive && gaugefix!(lq_householder!, computeL ? L : nothing, Q, diagview(A))
157173
else
158174
A, τ = gelqf!(driver, A)
175+
computeL && _lq_copyL!(L, A)
176+
Lf = computeL ? L : nothing
159177
if inplaceQ
160-
Q = unglq!(driver, A, τ)
178+
Ld = positive ? copy(diagview(A)) : nothing # unglq! destroys the diagonal of A
179+
unglq!(driver, A, τ) # Q === A, so no need to rebind Q
180+
positive && gaugefix!(lq_householder!, Lf, Q, Ld)
161181
else
162182
Q = unmlq!(driver, 'R', 'N', A, τ, one!(Q))
183+
positive && gaugefix!(lq_householder!, Lf, Q, diagview(A))
163184
end
164185
end
165186

166-
if computeL
167-
# we need to first copy then gaugefix - avoiding aliasing between L and Ld for broadcast
168-
Ld = diagview(A)
169-
copyto!(L, lowertriangular!(view(A, axes(L)...)))
170-
positive && gaugefix!(lq_householder!, L, Q, Ld)
171-
else
172-
gaugefix!(lq_householder!, nothing, Q, diagview(A))
173-
end
174-
175187
return L, Q
176188
end
177189
function lq_householder!(
@@ -183,6 +195,8 @@ function lq_householder!(
183195
throw(ArgumentError(lazy"$driver does not provide a blocked LQ decomposition"))
184196
pivoted &&
185197
throw(ArgumentError(lazy"$driver does not provide a pivoted LQ decomposition"))
198+
Q === A &&
199+
throw(ArgumentError(lazy"$driver does not provide an inplace Q"))
186200
# positive = true regardless of setting
187201

188202
m, n = size(A)
@@ -303,6 +317,9 @@ end
303317
function lq_via_qr!(
304318
A::AbstractMatrix, L::AbstractMatrix, Q::AbstractMatrix, qr_alg::AbstractAlgorithm
305319
)
320+
# Q is written before L, so an L that aliases A would corrupt an inplace Q
321+
(A === Q && !isempty(L) && Base.mightalias(L, A)) &&
322+
throw(ArgumentError("in-place Q is only supported if L does not share memory with A"))
306323
At = adjoint!(similar(A'), A)::AbstractMatrix
307324
Qt = (A === Q) ? At : similar(Q')
308325
Lt = similar(L')

‎src/implementations/qr.jl‎

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,30 @@ for f in (:geqrt!, :gemqrt!, :geqp3!, :geqrf!, :ungqr!, :unmqr!)
125125
end
126126
end
127127

128+
# cuSOLVER generates Q faster with ungqr! than by applying the reflectors with unmqr!,
129+
# and avoids the large workspace of ormqr, whose 32-bit size query fails for large matrices
130+
prefers_ungqr(::Driver) = false
131+
132+
# copy R out of the packed factorization, leaving the reflectors in A intact
133+
function _qr_copyR!(R::AbstractMatrix, A::AbstractMatrix, jpvt = nothing)
134+
Rp = isnothing(jpvt) ? R : view(R, :, jpvt)
135+
copyto!(Rp, view(A, axes(R)...))
136+
uppertriangular!(Rp)
137+
return R
138+
end
139+
140+
function _qr_buildQ!(driver::Driver, Q::AbstractMatrix, A::AbstractMatrix, τ, minmn::Int)
141+
if prefers_ungqr(driver)
142+
# build Q in its own space: copy in the reflectors, unit vectors elsewhere
143+
size(Q, 2) > minmn && one!(Q)
144+
copyto!(view(Q, :, 1:minmn), view(A, :, 1:minmn))
145+
ungqr!(driver, Q, τ)
146+
else
147+
Q = unmqr!(driver, 'L', 'N', A, τ, one!(Q))
148+
end
149+
return Q
150+
end
151+
128152
@inline qr_householder!(A, Q, R; driver::Driver = DefaultDriver(), kwargs...) =
129153
qr_householder!(driver, A, Q, R; kwargs...)
130154
qr_householder!(::DefaultDriver, A, Q, R; kwargs...) =
@@ -149,41 +173,45 @@ function qr_householder!(
149173
computeR = length(R) > 0
150174
inplaceQ = Q === A
151175

152-
(inplaceQ && (computeR || positive || blocksize > 1 || m < n)) &&
153-
throw(ArgumentError("inplace Q only supported if matrix is tall (`m >= n`), R is not required, and using the unblocked algorithm (`blocksize = 1`) with `positive = false`"))
176+
if inplaceQ
177+
# ungqr! builds Q in the space of A, so R has to be extracted first and cannot alias A
178+
(blocksize == 1 && m >= n) ||
179+
throw(ArgumentError(lazy"in-place Q is only supported if matrix is tall (`$m >= $n`) and using the unblocked algorithm (`blocksize = $blocksize`)"))
180+
(computeR && Base.mightalias(R, A)) &&
181+
throw(ArgumentError("in-place Q is only supported if R does not share memory with A"))
182+
end
154183

155184
# Compute QR in packed form
156185
if blocksize > 1
186+
# R doubles as workspace for T, so Q is constructed before R is extracted
157187
nb = min(minmn, blocksize)
158188
if computeR # first use R as space for T
159189
A, T = geqrt!(driver, A, view(R, 1:nb, 1:minmn))
160190
else
161191
A, T = geqrt!(driver, A, similar(A, nb, minmn))
162192
end
163193
Q = gemqrt!(driver, 'L', 'N', A, T, one!(Q))
194+
computeR && _qr_copyR!(R, A)
195+
positive && gaugefix!(qr_householder!, Q, computeR ? R : nothing, diagview(A))
164196
else
165197
if pivoted
166198
A, τ, jpvt = geqp3!(driver, A)
199+
computeR && _qr_copyR!(R, A, jpvt)
167200
else
168201
A, τ = geqrf!(driver, A)
202+
computeR && _qr_copyR!(R, A)
169203
end
204+
Rf = computeR ? R : nothing # gaugefix! rescales rows, which commutes with the pivoting
170205
if inplaceQ
171-
Q = ungqr!(driver, A, τ)
206+
Rd = positive ? copy(diagview(A)) : nothing # ungqr! destroys the diagonal of A
207+
ungqr!(driver, A, τ) # Q === A, so no need to rebind Q
208+
positive && gaugefix!(qr_householder!, Q, Rf, Rd)
172209
else
173-
Q = unmqr!(driver, 'L', 'N', A, τ, one!(Q))
210+
Q = _qr_buildQ!(driver, Q, A, τ, minmn)
211+
positive && gaugefix!(qr_householder!, Q, Rf, diagview(A))
174212
end
175213
end
176214

177-
if computeR
178-
# we need to first copy then gaugefix - avoiding aliasing between R and Rd for broadcast
179-
Rd = diagview(A)
180-
Rf = pivoted ? view(R, :, jpvt) : R
181-
copyto!(Rf, uppertriangular!(view(A, axes(R)...)))
182-
positive && gaugefix!(qr_householder!, Q, Rf, Rd)
183-
elseif positive
184-
gaugefix!(qr_householder!, Q, nothing, diagview(A))
185-
end
186-
187215
return Q, R
188216
end
189217
function qr_householder!(
@@ -195,6 +223,8 @@ function qr_householder!(
195223
throw(ArgumentError(lazy"$driver does not provide a blocked QR decomposition"))
196224
pivoted &&
197225
throw(ArgumentError(lazy"$driver does not provide a pivoted QR decomposition"))
226+
Q === A &&
227+
throw(ArgumentError(lazy"$driver does not provide an in-place Q"))
198228
# positive = true regardless of setting
199229

200230
m, n = size(A)

‎src/interface/decompositions.jl‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ Algorithm type to denote the algorithm for computing QR, RQ, QL or LQ decomposit
7676
7777
Depending on the driver, various other keywords may be (un)available to customize the implementation.
7878
The optional `driver` keyword can be used to choose between different implementations of this algorithm.
79+
80+
`Q` may be computed in the space of the input matrix `A`, by supplying `A` itself as output for
81+
`Q`. This requires `blocksize = 1`, a tall `A` for QR (a wide `A` for LQ), and `R` (or `L`) to not
82+
share memory with `A`.
7983
"""
8084
@algdef Householder
8185
function Householder(;

‎test/decompositions/lq.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ for T in (BLASFloats..., GenericFloats...), n in (37, m, 63)
5757
)
5858
TestSuite.test_lq_algs(T, (m, n), LAPACK_LQ_ALGS)
5959
elseif T ∈ GenericFloats
60-
TestSuite.test_lq(T, (m, n); test_pivoted = false, test_blocksize = false)
60+
TestSuite.test_lq(T, (m, n); test_pivoted = false, test_blocksize = false, test_inplaceQ = false)
6161
GENERIC_LQ_ALGS = (Householder(; driver = Native()), LQViaTransposedQR(Householder(; driver = GLA())))
6262
TestSuite.test_lq_algs(T, (m, n), GENERIC_LQ_ALGS)
6363
end

‎test/decompositions/qr.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ for T in (BLASFloats..., GenericFloats...), n in (37, m, 63)
5656
)
5757
TestSuite.test_qr_algs(T, (m, n), LAPACK_QR_ALGS)
5858
elseif T ∈ GenericFloats
59-
TestSuite.test_qr(T, (m, n); test_pivoted = false, test_blocksize = false)
59+
TestSuite.test_qr(T, (m, n); test_pivoted = false, test_blocksize = false, test_inplaceQ = false)
6060
GENERIC_QR_ALGS = (Householder(; driver = Native()), Householder(; driver = GLA()))
6161
TestSuite.test_qr_algs(T, (m, n), GENERIC_QR_ALGS)
6262
end

‎test/testsuite/decompositions/lq.jl‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ function test_lq(T::Type, sz; test_null = true, kwargs...)
66
test_lq_compact(T, sz; kwargs...)
77
test_lq_full(T, sz; kwargs...)
88
test_null && test_lq_null(T, sz; kwargs...)
9+
test_lq_inplaceQ(T, sz; kwargs...)
910
end
1011
end
1112

@@ -75,6 +76,61 @@ function test_lq_compact(
7576
end
7677
end
7778

79+
# test using `A` itself as output for `Q`
80+
function test_lq_inplaceQ(
81+
T::Type, sz;
82+
test_inplaceQ = true, test_positive = true,
83+
atol::Real = 0, rtol::Real = precision(T),
84+
kwargs...
85+
)
86+
(sz isa Tuple && length(sz) == 2) || return nothing
87+
m, n = sz
88+
n >= m || return nothing # inplace Q requires a wide matrix
89+
summary_str = testargs_summary(T, sz)
90+
return @testset "lq_compact! inplace Q $summary_str" begin
91+
A = instantiate_matrix(T, sz)
92+
L = similar(A, (m, m))
93+
94+
if !test_inplaceQ
95+
Ain = deepcopy(A)
96+
@test_throws Exception lq_compact!(Ain, (L, Ain))
97+
else
98+
for positive in (test_positive ? (false, true) : (false,))
99+
Ain = deepcopy(A)
100+
L2, Q = lq_compact!(Ain, (L, Ain); positive)
101+
@test Q === Ain
102+
@test L2 * Q ≈ A
103+
@test isisometric(Q; side = :right, atol, rtol)
104+
@test istril(L2)
105+
if positive
106+
@test has_positive_diagonal(L2)
107+
end
108+
109+
# L is not required
110+
Ain2 = deepcopy(A)
111+
_, Q2 = lq_compact!(Ain2, (similar(A, (0, 0)), Ain2); positive)
112+
@test Q2 === Ain2
113+
@test Q2 ≈ Q
114+
end
115+
116+
if m == n
117+
Ain = deepcopy(A)
118+
Lf, Q = lq_full!(Ain, (similar(A, (m, n)), Ain))
119+
@test Q === Ain
120+
@test Lf * Q ≈ A
121+
@test isunitary(Q; atol, rtol)
122+
@test has_positive_diagonal(Lf)
123+
end
124+
125+
# blocked algorithm and aliased L are not supported
126+
Ain = deepcopy(A)
127+
@test_throws ArgumentError lq_compact!(Ain, (L, Ain); blocksize = 2)
128+
Ain = deepcopy(A)
129+
@test_throws ArgumentError lq_compact!(Ain, (view(Ain, :, 1:m), Ain))
130+
end
131+
end
132+
end
133+
78134
function test_lq_compact_algs(
79135
T::Type, sz, algs;
80136
atol::Real = 0, rtol::Real = precision(T),

‎test/testsuite/decompositions/qr.jl‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ function test_qr(T::Type, sz; kwargs...)
66
test_qr_compact(T, sz; kwargs...)
77
test_qr_full(T, sz; kwargs...)
88
test_qr_null(T, sz; kwargs...)
9+
test_qr_inplaceQ(T, sz; kwargs...)
910
end
1011
end
1112

@@ -112,6 +113,65 @@ function test_qr_compact_algs(
112113
end
113114
end
114115

116+
# test using `A` itself as output for `Q`
117+
function test_qr_inplaceQ(
118+
T::Type, sz;
119+
test_inplaceQ = true, test_positive = true, test_pivoted = true,
120+
atol::Real = 0, rtol::Real = precision(T),
121+
kwargs...
122+
)
123+
(sz isa Tuple && length(sz) == 2) || return nothing
124+
m, n = sz
125+
m >= n || return nothing # inplace Q requires a tall matrix
126+
summary_str = testargs_summary(T, sz)
127+
return @testset "qr_compact! inplace Q $summary_str" begin
128+
A = instantiate_matrix(T, sz)
129+
R = similar(A, (n, n))
130+
131+
if !test_inplaceQ
132+
Ain = deepcopy(A)
133+
@test_throws Exception qr_compact!(Ain, (Ain, R))
134+
else
135+
for positive in (test_positive ? (false, true) : (false,)),
136+
pivoted in (test_pivoted ? (false, true) : (false,))
137+
138+
Ain = deepcopy(A)
139+
Q, R2 = qr_compact!(Ain, (Ain, R); positive, pivoted)
140+
@test Q === Ain
141+
@test Q * R2 ≈ A
142+
@test isisometric(Q; atol, rtol)
143+
if !pivoted
144+
@test istriu(R2)
145+
if positive
146+
@test has_positive_diagonal(R2)
147+
end
148+
end
149+
150+
# R is not required
151+
Ain2 = deepcopy(A)
152+
Q2, = qr_compact!(Ain2, (Ain2, similar(A, (0, 0))); positive, pivoted)
153+
@test Q2 === Ain2
154+
@test Q2 ≈ Q
155+
end
156+
157+
if m == n
158+
Ain = deepcopy(A)
159+
Q, Rf = qr_full!(Ain, (Ain, similar(A, (m, n))))
160+
@test Q === Ain
161+
@test Q * Rf ≈ A
162+
@test isunitary(Q; atol, rtol)
163+
@test has_positive_diagonal(Rf)
164+
end
165+
166+
# blocked algorithm and aliased R are not supported
167+
Ain = deepcopy(A)
168+
@test_throws ArgumentError qr_compact!(Ain, (Ain, R); blocksize = 2)
169+
Ain = deepcopy(A)
170+
@test_throws ArgumentError qr_compact!(Ain, (Ain, view(Ain, 1:n, :)))
171+
end
172+
end
173+
end
174+
115175
function test_qr_full(
116176
T::Type, sz;
117177
test_positive = true, test_pivoted = true, test_blocksize = true,

0 commit comments

Comments
 (0)