Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

2026-09-28 QR Retrospective

Last time

  • Right vs left-looking algorithms

  • Elementary reflectors

  • Householder QR

Today

  • Householder fix

  • Comparison of interfaces

  • Profiling

  • Cholesky QR

using LinearAlgebra
using Plots
default(linewidth=4, legendfontsize=12)

function vander(x, k=nothing)
    if isnothing(k)
        k = length(x)
    end
    m = length(x)
    V = ones(m, k)
    for j in 2:k
        V[:, j] = V[:, j-1] .* x
    end
    V
end

function gram_schmidt_classical(A)
    m, n = size(A)
    Q = zeros(m, n)
    R = zeros(n, n)
    for j in 1:n
        v = A[:,j]
        R[1:j-1,j] = Q[:,1:j-1]' * v
        v -= Q[:,1:j-1] * R[1:j-1,j]
        R[j,j] = norm(v)
        Q[:,j] = v / R[j,j]
    end
    Q, R
end
gram_schmidt_classical (generic function with 1 method)

Householder QR

Gram-Schmidt constructed a triangular matrix RR to orthogonalize AA into QQ. Each step was a projector, which is a rank-deficient operation. Householder uses orthogonal transformations (reflectors) to triangularize.

Qn⋯Q1⏟QTA=R\underbrace{Q_{n} \dotsb Q_1}_{Q^T} A = R

The structure of the algorithm is

[∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗]⏟A→[∗∗∗0∗∗0∗∗0∗∗0∗∗]⏟Q1A→[∗∗∗0∗∗00∗00∗00∗]⏟Q2Q1A→[∗∗∗0∗∗00∗000000]⏟Q3Q2Q1A\underbrace{\begin{bmatrix} * & * & * \\ * & * & * \\ * & * & * \\ * & * & * \\ * & * & * \\ \end{bmatrix}}_{A} \to \underbrace{\begin{bmatrix} * & * & * \\ 0 & * & * \\ 0 & * & * \\ 0 & * & * \\ 0 & * & * \\ \end{bmatrix}}_{Q_1 A} \to \underbrace{\begin{bmatrix} * & * & * \\ 0 & * & * \\ 0 & 0 & * \\ 0 & 0 & * \\ 0 & 0 & * \\ \end{bmatrix}}_{Q_2 Q_1 A} \to \underbrace{\begin{bmatrix} * & * & * \\ 0 & * & * \\ 0 & 0 & * \\ 0 & 0 & 0 \\ 0 & 0 & 0 \\ \end{bmatrix}}_{Q_3 Q_2 Q_1 A}

Constructing the QjQ_j

Qn⋯Q1⏟QTA=R\underbrace{Q_{n} \dotsb Q_1}_{Q^T} A = R

Each of our QjQ_j will have the form

Qj=[Ii00F]Q_j = \begin{bmatrix} I_i & 0 \\ 0 & F \end{bmatrix}

where FF is a “reflection” that achieves

Fx=[∥x∥00⋮]F x = \begin{bmatrix} \lVert x \rVert \\ 0 \\ 0 \\ \vdots \end{bmatrix}

where xx is the column of RR from the diagonal down. This transformation is a reflection across a plane with normal v=Fx−x=∥x∥e1−xv = Fx - x = \lVert x \rVert e_1 - x.

Householder Reflector (Trefethen and Bau, 1999)

The reflection, as depicted above by Trefethen and Bau (1999) can be written F=I−2vvTvTvF = I - 2 \frac{v v^T}{v^T v}.

Adventures in reflection

A = rand(4, 4); A += A'
v = copy(A[:,1])
v[1] -= norm(v)
v = normalize(v)
F = I - 2 * v * v'
B = F * A
4×4 Matrix{Float64}: 2.68473 2.24213 1.49483 2.48211 9.79724e-17 -0.270069 0.196389 0.915463 1.19184e-16 -0.319677 -0.317452 0.238797 -2.06218e-16 -0.591514 -0.194604 -0.585453
v = copy(B[2:end, 2])
v[1] -= norm(v); v = normalize(v)
F = I - 2 * v * v'
B[2:end, 2:end] = F * B[2:end, 2:end]
B
4×4 Matrix{Float64}: 2.68473 2.24213 1.49483 2.48211 9.79724e-17 0.724583 0.225722 0.0313666 1.19184e-16 5.55112e-17 -0.308024 -0.0453481 -2.06218e-16 5.55112e-17 -0.177159 -1.11122

An algorithm

function qr_householder_naive(A)
    m, n = size(A)
    R = copy(A)
    V = [] # list of reflectors
    for j in 1:n
        v = copy(R[j:end, j])
        v[1] -= norm(v)
        v = normalize(v)
        R[j:end,j:end] -= 2 * v * (v' * R[j:end,j:end])
        push!(V, v)
    end
    V, R
end
qr_householder_naive (generic function with 1 method)
m = 4
x = LinRange(-1, 1, m)
A = vander(x, m)
V, R = qr_householder_naive(A)
_, R_ = qr(A)
R_
4×4 Matrix{Float64}: -2.0 0.0 -1.11111 0.0 0.0 1.49071 1.38778e-17 1.3582 0.0 0.0 0.888889 9.71445e-17 0.0 0.0 0.0 0.397523

How to interpret VV as QQ?

function reflectors_mult(V, x)
    y = copy(x)
    for v in reverse(V)
        n = length(v) - 1
        y[end-n:end] -= 2 * v * (v' * y[end-n:end])
    end
    y
end

function reflectors_to_dense(V)
    m = length(V[1])
    Q = diagm(ones(m))
    for j in 1:m
        Q[:,j] = reflectors_mult(V, Q[:,j])
    end
    Q
end
reflectors_to_dense (generic function with 1 method)
m = 20
x = LinRange(-1, 1, m)
A = vander(x, m)
V, R = qr_householder_naive(A)
Q = reflectors_to_dense(V)
@show norm(Q' * Q - I)
@show norm(Q * R - A);
norm(Q' * Q - I) = 3.7994490775439526e-15
norm(Q * R - A) = 7.562760794606217e-15

Great, but we can still break it

#A = [1.0 0; 0 1]
A = [0 2; 1e-2 1.]
V, R = qr_householder_naive(A)
#Q, R = qr(A)
R
2×2 Matrix{Float64}: 0.01 1.0 -1.73472e-18 NaN

We had the lines

    v = copy(R[j:end, j])
    v[1] -= norm(v)
    v = normalize(v)

What happens when R is already upper triangular?

Choosing the better of two Householder reflectors (Trefethen and Bau, 1999).

An improved algorithm

function qr_householder(A)
    m, n = size(A)
    R = copy(A)
    V = [] # list of reflectors
    for j in 1:n
        v = copy(R[j:end, j])
        #v[1] += sign(v[1]) * norm(v) # <---
        v[1] += (v[1] > 0 ? 1 : -1) * norm(v)
        v = normalize(v)
        R[j:end,j:end] -= 2 * v * v' * R[j:end,j:end]
        push!(V, v)
    end
    V, R
end
qr_householder (generic function with 1 method)
A = [2 -1; -1 2] * 1e-10
V, R = qr_householder(A)
tau = [2*v[1]^2 for v in V]
@show tau
V1 = [v ./ v[1] for v in V]
@show V1
R
tau = [1.894427190999916, 2.0]
V1 = [[1.0, -0.2360679774997897], [1.0]]
2×2 Matrix{Float64}: -2.23607e-10 1.78885e-10 -1.29247e-26 -1.34164e-10

Householder is backward stable

m = 40
x = LinRange(-1, 1, m)
A = vander(x, m)
V, R = qr_householder(A)
Q = reflectors_to_dense(V)
@show norm(Q' * Q - I)
@show norm(Q * R - A);
norm(Q' * Q - I) = 5.949301496893686e-15
norm(Q * R - A) = 1.2090264267288813e-14
A = [1 0; 0 1.]
V, R = qr_householder(A)
#qr(A)
(Any[[1.0, 0.0], [1.0]], [-1.0 0.0; 0.0 -1.0])

Orthogonality is preserved

x = LinRange(-1, 1, 20)
A = vander(x)
Q, _ = gram_schmidt_classical(A)
v = A[:,end]
@show norm(v)
scatter(abs.(Q[:,1:end-1]' * v), yscale=:log10, title="Classical Gram-Schmidt")
norm(v) = 1.4245900685395503
Loading...
Q = reflectors_to_dense(qr_householder(A)[1])
scatter(abs.(Q[:,1:end-1]' * v), yscale=:log10, title="Householder QR")
Loading...

Composition of reflectors

(I−2vvT)(I−2wwT)=I−2vvT−2wwT+4v(vTw)wT=I−[v∣w][2−4vTw02][vTwT]\begin{align} (I - 2 v v^T) (I - 2 w w^T) &= I - 2 v v^T - 2 w w^T + 4 v (v^T w) w^T \\ &= I - \Bigg[v \Bigg| w \Bigg] \begin{bmatrix} 2 & -4 v^T w \\ 0 & 2 \end{bmatrix} \begin{bmatrix} v^T \\ w^T \end{bmatrix} \end{align}

This turns applying reflectors from a sequence of vector operations to a sequence of (smallish) matrix operations. It’s the key to high performance and the native format (QRCompactWY) returned by Julia qr().

Q, R = qr(A[:, 1:5])
LinearAlgebra.QRCompactWY{Float64, Matrix{Float64}, Matrix{Float64}} Q factor: 20×20 LinearAlgebra.QRCompactWYQ{Float64, Matrix{Float64}, Matrix{Float64}} R factor: 5×5 Matrix{Float64}: -4.47214 0.0 -1.64763 0.0 -1.08899 0.0 2.71448 1.11022e-16 1.79412 -2.22045e-16 0.0 0.0 -1.46813 5.55112e-17 -1.37924 0.0 0.0 0.0 -0.774796 1.66533e-16 0.0 0.0 0.0 0.0 0.402707

This works even for very nonsquare matrices

A = rand(1000000, 5)
Q, R = qr(A)
@show size(Q)
@show norm(Q*R - A)
R
size(Q) = (1000000, 1000000)
norm(Q * R - A) = 4.103993514007667e-12
5×5 Matrix{Float64}: -577.782 -433.374 -433.314 -432.929 -432.852 0.0 381.589 163.282 163.051 163.235 0.0 0.0 -345.047 -103.392 -103.448 0.0 0.0 0.0 329.173 76.3907 0.0 0.0 0.0 0.0 -320.405

This is known as a “full” (or “complete”) QR factorization, in contrast to a reduced QR factorization in which QQ has the same shape as AA.

  • How much memory does QQ use?

Compare to numpy.linalg.qr

  • Need to decide up-front whether you want full or reduced QR.

  • Full QR is expensive to represent.

Cholesky QR

RTR=(QR)TQR=ATAR^T R = (QR)^T QR = A^T A

so we should be able to use LLT=ATAL L^T = A^T A and then Q=AL−TQ = A L^{-T}.

function qr_chol(A)
    R = cholesky(A' * A).U
    Q = A / R
    Q, R
end

A = rand(10,4)
Q, R = qr_chol(A)
@show norm(Q' * Q - I)
@show norm(Q * R - A)
norm(Q' * Q - I) = 1.4610813375536948e-15
norm(Q * R - A) = 2.237726045655905e-16
2.237726045655905e-16
x = LinRange(-1, 1, 20)
A = vander(x)
Q, R = qr_chol(A)
@show norm(Q' * Q - I)
@show norm(Q * R - A);
norm(Q' * Q - I) = 0.1749736012761826
norm(Q * R - A) = 6.520306397146206e-16

Can we fix this?

Note that the product of two triangular matrices is triangular.

R = triu(rand(5,5))
R * R
5×5 Matrix{Float64}: 0.453167 0.972976 1.01752 1.26301 1.10259 0.0 0.993084 0.919986 1.32044 1.08722 0.0 0.0 0.276985 0.796827 0.437453 0.0 0.0 0.0 0.902163 0.751084 0.0 0.0 0.0 0.0 0.77306
function qr_chol2(A)
    Q, R = qr_chol(A)
    Q, R1 = qr_chol(Q)
    Q, R1 * R
end

x = LinRange(-1, 1, 20)
A = vander(x)
Q, R = qr_chol2(A)
@show norm(Q' * Q - I)
@show norm(Q * R - A);
norm(Q' * Q - I) = 1.3276319786294278e-15
norm(Q * R - A) = 1.0894860257129427e-15

How fast are these methods?

m, n = 5000, 1000
A = randn(m, n)

@time qr(A);
  0.169613 seconds (15 allocations: 38.698 MiB, 0.81% gc time)
A = randn(m, n)
@time qr_chol2(A);
  0.199483 seconds (22 allocations: 114.444 MiB, 15.33% gc time)

Profiling

using ProfileSVG

@profview qr(A)
#@profview qr_chol(A)
Loading...

Krylov subspaces

Suppose we wish to solve

Ax=bA x = b

but only have the ability to apply the action of the AA (we do not have access to its entries). A general approach is to work with approximations in a Krylov subspace, which has the form

Kn=[b∣Ab∣A2b∣⋯∣An−1b].K_n = \big[ b \big| Ab \big| A^2 b \big| \dotsm \big| A^{n-1} b \big] .

This matrix is horribly ill-conditioned and cannot stably be computed as written. Instead, we seek an orthogonal basis QnQ_n that spans the same space as KnK_n. We could write this as a factorization

Kn=QnRnK_n = Q_n R_n

where the first column q1=b/∥b∥q_1 = b / \lVert b \rVert. The RnR_n is unnecessary and hopelessly ill-conditioned, so a slightly different procedure is used.

Arnoldi iteration

The Arnoldi iteration applies orthogonal similarity transformations to reduce AA to Hessenberg form, starting from a vector q1=b/∥b∥q_1 = b/\lVert b \rVert,

A=QHQ∗.A = Q H Q^* .

Let’s multiply on the right by QQ and examine the first nn columns,

AQn=Qn+1HnA Q_n = Q_{n+1} H_n

where HnH_n is an (n+1)×n(n+1) \times n Hessenberg matrix.

GMRES

AQn=Qn+1HnA Q_n = Q_{n+1} H_n

GMRES (Generalized Minimum Residual) minimizes

∥Ax−b∥\lVert A x - b \rVert

over the subspace QnQ_n. I.e., x=Qnyx = Q_n y for some yy. By the Arnoldi recurrence, this is equivalent to

∥Qn+1Hny−b∥\lVert Q_{n+1} H_n y - b \lVert

which can be solved by minimizing

∥Hny−Qn+1∗b∥.\lVert H_n y - Q_{n+1}^* b \rVert .

Since q1=b/∥b∥q_1 = b/\lVert b \lVert, the least squares problem is to minimize

∥Hny−∥b∥e1∥.\Big\lVert H_n y - \lVert b \rVert e_1 \Big\rVert .

The solution of this least squares problem is achieved by incrementally updating a QRQR factorization of HnH_n.

Notes

  • The solution xnx_n constructed by GMRES at iteration nn is not explicitly available. If a solution is needed, it must be constructed by solving the (n+1)×n(n+1)\times n least squares problem and forming the solution as a linear combination of the nn vectors QnQ_n. The leading cost is 2mn2mn where m≫nm \gg n.

  • The residual vector rn=Axn−br_n = A x_n - b is not explicitly available in GMRES. To compute it, first build the solution xn=Qnynx_n = Q_n y_n.

  • GMRES minimizes the 2-norm of the residual ∥rn∥\lVert r_n \rVert which is equivalent to the A∗AA^* A norm of the error ∥xn−x∗∥A∗A\lVert x_n - x_* \rVert_{A^* A}.

More notes on GMRES

  • GMRES needs to store the full QnQ_n, which is unaffordable for large nn (many iterations). The standard solution is to choose a “restart” kk and to discard QnQ_n and start over with an initial guess xkx_k after each kk iterations. This algorithm is called GMRES(k). PETSc’s default solver is GMRES(30) and the restart can be controlled using the run-time option -ksp_gmres_restart.

  • Most implementations of GMRES use classical Gram-Schmidt because it is much faster in parallel (one reduction per iteration instead of nn reductions per iteration). The PETSc option -ksp_gmres_modifiedgramschmidt can be used when you suspect that classical Gram-Schmidt may be causing instability.

  • There is a very similar (and older) algorithm called GCR that maintains xnx_n and rnr_n. This is useful, for example, if a convergence tolerance needs to inspect individual entries. GCR requires 2n2n vectors instead of nn vectors, and can tolerate a nonlinear preconditioner. FGMRES is a newer algorithm with similar properties to GCR.