Skip to content

9.3 Orthogonality, Householder QR, and orthogonal initialization

Once you start initializing networks, one problem appears almost immediately. The first recurrent model, Vanilla RNN with manual BPTT and truncation in AI Engineering, multiplies its hidden state by the same matrix WW at every one of hundreds of steps. If WW stretches some direction by 1.1, that direction grows by 1.1100≈13 7811.1^{100} \approx 13\,781; if it shrinks one by 0.9, the gradient along it falls to 0.9100≈2.7×10−50.9^{100} \approx 2.7 \times 10^{-5}. A matrix that stretches nothing and shrinks nothing is an orthogonal one, and the standard way to produce a random one is the QR factorization of a Gaussian matrix.

Concepts from other sections (9)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

QR is also the engine of the next section, Eigenvalues, power iteration, and the spectral radius, which finds every eigenvalue’s size, including the complex ones that power iteration cannot see, by repeating QR. This section builds QR with Householder reflections, the version that stays accurate on the nearly dependent columns real weight matrices have, and then uses it to build an orthogonal initializer.

The solution is qr.py, with contract qr.pyi. It provides qr_householder(A), the reduced A=QRA = QR by reflections with diag⁡(R)≥0\operatorname{diag}(R) \ge 0, and orthogonal_init(shape, gain, rng), which makes weights with orthonormal rows or columns the way torch.nn.init.orthogonal_ does. The Gaussian matrix comes from the normal draws of Random variables, expectation, variance, and normal draws by Box-Muller (rv.py), and elimination from Gaussian elimination and LU with partial pivoting is the useful contrast.

Learning objectives

  • Show that a matrix with orthonormal columns preserves lengths and angles.
  • Explain why Householder QR stays orthogonal to machine precision when Gram-Schmidt does not.
  • Choose the sign of a Householder reflector so that it never cancels, and factor a 2 by 2 matrix by hand.
  • State the sign rule that makes QR unique and explain why it makes orthogonal initialization uniformly distributed.
  • Implement qr_householder and orthogonal_init and test them against LAPACK.

These symbols recur through the section:

SymbolMeaningType / shape
⟨u,v⟩=u⊤v\langle u, v \rangle = u^\top vinner (dot) productscalar
∥x∥=x⊤x\lVert x \rVert = \sqrt{x^\top x}Euclidean lengthscalar
AAthe matrix to factor, mm rows and nn columnsfloat64[m, n]
k=min⁡(m,n)k = \min(m, n)the number of columns of QQ in the reduced factorizationint
QQorthonormal columns: Q⊤Q=IkQ^\top Q = I_kfloat64[m, k]
RRupper triangular, non-negative diagonalfloat64[k, n]
e1e_1(1,0,…,0)(1, 0, \dots, 0)vector
vva unit vector defining a reflectionvector
H=I−2vv⊤H = I - 2vv^\topthe Householder reflection across the hyperplane orthogonal to vvsquare matrix
α\alphathe value a reflected column keeps in its first entryscalar
ggthe gain of the initializerscalar
ε\varepsilonfloat64 unit roundoff, about 1.1×10−161.1 \times 10^{-16}

Two vectors are orthogonal when ⟨u,v⟩=0\langle u, v \rangle = 0; a set of vectors is orthonormal when every pair is orthogonal and each has length 1. A matrix QQ whose columns are orthonormal satisfies Q⊤Q=IQ^\top Q = I, because entry (i,j)(i, j) of Q⊤QQ^\top Q is ⟨qi,qj⟩\langle q_i, q_j \rangle. Then

∥Qx∥2=x⊤Q⊤Qx=x⊤x=∥x∥2,⟨Qx,Qy⟩=⟨x,y⟩.\lVert Qx \rVert^2 = x^\top Q^\top Q x = x^\top x = \lVert x \rVert^2, \qquad \langle Qx, Qy \rangle = \langle x, y \rangle .

QQ preserves lengths and angles: multiplying by it can neither blow up nor shrink a signal. A square QQ with Q⊤Q=IQ^\top Q = I is an orthogonal matrix; its inverse is its transpose, and its columns and rows are both orthonormal.

Every real m×nm \times n matrix with m≥nm \ge n factors as A=QRA = QR, with QQ having orthonormal columns and RR upper triangular. The first jj columns of QQ span the first jj columns of AA, and RR holds the coordinates. The question is how to compute it without losing orthogonality.

The textbook construction, Gram-Schmidt, subtracts from each column its projections on the previous qq‘s and normalizes. In floating point it computes the projections with rounding errors, and when two columns are nearly parallel (condition number 101010^{10}), what is left after subtracting is mostly those errors: the computed qq‘s are far from orthogonal.

Householder takes the other route. It applies orthogonal matrices to AA until it becomes triangular, Hk−1⋯H1H0 A=RH_{k-1} \cdots H_1 H_0\, A = R, so Q=H0H1⋯Hk−1Q = H_0 H_1 \cdots H_{k-1}. Each Hj=I−2vv⊤H_j = I - 2 v v^\top with ∥v∥=1\lVert v \rVert = 1 is a reflection: it maps vv to −v-v and leaves every vector orthogonal to vv alone. It is symmetric and its own inverse (H2=I−4vv⊤+4v(v⊤v)v⊤=IH^2 = I - 4vv^\top + 4v(v^\top v)v^\top = I), hence orthogonal. Since QQ is a product of exactly orthogonal matrices, rounding errors only perturb it slightly: ∥Q⊤Q−I∥\lVert Q^\top Q - I \rVert stays near ε\varepsilon whatever the conditioning of AA.

That settles the strategy. The remaining question is which reflection to use at each step. Step jj looks at $x = $ column jj of the working matrix from row jj down, and wants a reflection that maps xx to αe1\alpha e_1, zeroing everything below the diagonal. Reflections preserve length, so ∣α∣=∥x∥\lvert \alpha \rvert = \lVert x \rVert, and the reflection that swaps xx and αe1\alpha e_1 has vv along their difference:

v=x−αe1∥x−αe1∥,Hx=αe1.v = \frac{x - \alpha e_1}{\lVert x - \alpha e_1 \rVert}, \qquad H x = \alpha e_1 .

Either sign of α\alpha works in exact arithmetic. In floating point, the first entry of x−αe1x - \alpha e_1 is x0−αx_0 - \alpha, and if α\alpha has the same sign as x0x_0 and xx is already almost along e1e_1, this subtracts two nearly equal numbers and leaves only rounding error. With x=(1,10−9,2×10−9)x = (1, 10^{-9}, 2 \times 10^{-9}), ∥x∥=1+2.5×10−18\lVert x \rVert = 1 + 2.5 \times 10^{-18}, which rounds to exactly 1, so x0−∥x∥=0x_0 - \lVert x \rVert = 0 and vv points the wrong way. The fix is to choose α=−sign⁡(x0)∥x∥\alpha = -\operatorname{sign}(x_0) \lVert x \rVert, with sign⁡(0)=+1\operatorname{sign}(0) = +1. Then x0−α=x0+sign⁡(x0)∥x∥x_0 - \alpha = x_0 + \operatorname{sign}(x_0)\lVert x \rVert adds two numbers of the same sign and never cancels. If ∥x∥=0\lVert x \rVert = 0 the column is already zero and the step is skipped.

Applying HH never forms the m×mm \times m matrix: HB=B−2v(v⊤B)H B = B - 2 v (v^\top B) costs one product and one outer product. The solution applies it to the trailing block of RR (columns jj onward) and accumulates Q←QHQ \leftarrow Q H as Q−2(Qv)v⊤Q - 2(Qv)v^\top on columns jj onward, then writes α\alpha and exact zeros into column jj.

QR as described is not quite unique. If A=QRA = QR, then also A=(QD)(DR)A = (QD)(DR) for any diagonal DD of ±1\pm 1‘s, since D2=ID^2 = I. Fixing diag⁡(R)≥0\operatorname{diag}(R) \ge 0 removes that freedom: for a matrix of full column rank the reduced factorization with a positive diagonal is unique. The contract applies the rule at the end: di=−1d_i = -1 where Rii<0R_{ii} < 0, else +1+1; then Q←Qdiag⁡(d)Q \leftarrow Q\operatorname{diag}(d) and R←diag⁡(d)RR \leftarrow \operatorname{diag}(d) R. LAPACK (np.linalg.qr) uses its own signs, so a comparison applies the same rule to NumPy’s answer before comparing entries.

A wide matrix (m<nm < n) gives k=mk = m: QQ is square and RR is m×nm \times n, upper trapezoidal. A tall one gives k=nk = n.

With a unique, stable QR in hand, the initializer is a short recipe. torch.nn.init.orthogonal_ builds a weight of shape (r,c)(r, c) like this: draw GG with independent standard normal entries; if r<cr < c, factor G⊤G^\top instead; take QQ from QR with the sign rule; transpose back if needed; multiply by the gain gg. The result has orthonormal columns (tall) or rows (wide), scaled by gg, so every singular value equals gg and W⊤W=g2IW^\top W = g^2 I (or WW⊤=g2IWW^\top = g^2 I).

The sign rule is what makes QQ uniformly distributed over orthogonal matrices (the Haar measure). The Gaussian distribution of GG is unchanged by any orthogonal transformation, so the distribution of QQ would be too, except that the factorization’s own sign convention couples QQ‘s signs to RR‘s. With this section’s reflector convention, R00=αR_{00} = \alpha always has the opposite sign of G00G_{00}, so without the rule Q00=G00/R00Q_{00} = G_{00}/R_{00} would be negative every single time. With the rule, Q00=G00/∥G:,0∥Q_{00} = G_{00}/\lVert G_{:,0} \rVert is positive exactly half the time (Mezzadri 2007).

The draw is also deterministic: GG is normal(rng, r * c) reshaped in C order, so the same generator state gives the same weights in every run.

Factor

A=(3142).A = \begin{pmatrix} 3 & 1 \\ 4 & 2 \end{pmatrix}.

One reflector suffices (j=0j = 0), since a 2×22 \times 2 matrix has one entry below the diagonal. The table walks through it quantity by quantity:

QuantityValue
xx = column 0(3,4)(3, 4), ∥x∥=5\lVert x \rVert = 5
α=−sign⁡(3)⋅5\alpha = -\operatorname{sign}(3) \cdot 5−5-5
x−αe1x - \alpha e_1(3+5,4)=(8,4)(3 + 5, 4) = (8, 4), length 80\sqrt{80}
H=I−2 (8,4)(8,4)⊤80H = I - 2\,\frac{(8, 4)(8, 4)^\top}{80}I−140(64323216)=(−0.6−0.8−0.80.6)I - \frac{1}{40}\begin{pmatrix} 64 & 32 \\ 32 & 16 \end{pmatrix} = \begin{pmatrix} -0.6 & -0.8 \\ -0.8 & 0.6 \end{pmatrix}
H⋅H \cdot column 0(−0.6⋅3−0.8⋅4, −0.8⋅3+0.6⋅4)=(−5,0)(-0.6 \cdot 3 - 0.8 \cdot 4,\ -0.8 \cdot 3 + 0.6 \cdot 4) = (-5, 0)
H⋅H \cdot column 1(−0.6−1.6, −0.8+1.2)=(−2.2,0.4)(-0.6 - 1.6,\ -0.8 + 1.2) = (-2.2, 0.4)

So R=(−5−2.200.4)R = \begin{pmatrix} -5 & -2.2 \\ 0 & 0.4 \end{pmatrix} and Q=HQ = H. The sign rule flips row 0 of RR and column 0 of QQ (only R00R_{00} is negative):

Q=(0.6−0.80.80.6),R=(52.200.4).Q = \begin{pmatrix} 0.6 & -0.8 \\ 0.8 & 0.6 \end{pmatrix}, \qquad R = \begin{pmatrix} 5 & 2.2 \\ 0 & 0.4 \end{pmatrix}.

Check: QR=(0.6⋅50.6⋅2.2−0.8⋅0.40.8⋅50.8⋅2.2+0.6⋅0.4)=(3142)QR = \begin{pmatrix} 0.6 \cdot 5 & 0.6 \cdot 2.2 - 0.8 \cdot 0.4 \\ 0.8 \cdot 5 & 0.8 \cdot 2.2 + 0.6 \cdot 0.4 \end{pmatrix} = \begin{pmatrix} 3 & 1 \\ 4 & 2 \end{pmatrix}, and the columns of QQ are orthonormal: 0.36+0.64=10.36 + 0.64 = 1, −0.48+0.48=0-0.48 + 0.48 = 0.

Two functions cover both uses:

def qr_householder(A: ArrayLike) -> tuple[NDArray, NDArray]:
"""Reduced QR, k = min(m, n): Q [m, k] with Q^T Q = I, R [k, n] upper
triangular with diag(R) >= 0, A == Q @ R. A is not modified."""
def orthogonal_init(shape: tuple[int, int], gain: float, rng) -> NDArray:
"""gain * (orthonormal rows or columns), from the QR of normal(rng, rows * cols)."""

qr_householder returns the reduced factorization, leaves its input alone, and rejects anything that is not two-dimensional. orthogonal_init rejects zero or negative dimensions so that configuration errors fail early.

The reasoning chain is short. QQ must be orthogonal to working precision whatever AA is, and building it as a product of reflections is the only one of the two constructions whose error does not grow with the conditioning of AA. So the algorithm is: for each column, reflect the part on and below the diagonal onto a multiple of e1e_1. The reflection must not cancel, which fixes α=−sign⁡(x0)∥x∥\alpha = -\operatorname{sign}(x_0)\lVert x\rVert with sign⁡(0)=+1\operatorname{sign}(0) = +1; in the worked example x=(3,4)x = (3, 4) gives α=−5\alpha = -5 and v∝(8,4)v \propto (8, 4).

HH is never formed: HB=B−2v(v⊤B)HB = B - 2v(v^\top B) costs O(rows⋅cols)O(\text{rows} \cdot \text{cols}) instead of a full matrix product. It is applied to R[j:, j:] only, since rows above jj are not touched by HjH_j and columns left of jj are already zero below the diagonal. Because A=H0H1⋯Hk−1RA = H_0 H_1 \cdots H_{k-1} R, QQ is accumulated by multiplying on the right, Q←QHjQ \leftarrow QH_j, and since HjH_j is the identity outside rows and columns jj onward, only Q[:, j:] changes.

A reflector is needed for each column that has entries below the diagonal, which is min(m - 1, n) steps: for a square matrix the last column has none, and for a wide matrix columns mm onward have no diagonal entry at all. A zero sub-column is already done and is skipped, which avoids 0/00/0. The reduced factorization keeps the first kk columns of QQ and rows of RR, and the sign rule then makes it unique and, for the initializer, Haar-distributed. Finally, the initializer needs orthonormal rows when the weight is wide; QR gives orthonormal columns only for a tall input, so a wide GG is factored as G⊤G^\top and the QQ transposed back.

Set up a working copy that becomes RR, and an m×mm \times m identity that becomes QQ:

def qr_householder(A: ArrayLike) -> tuple[NDArray, NDArray]:
R = np.array(A, dtype=np.float64) # a copy, reduced to R in place
if R.ndim != 2:
raise ValueError(f"qr_householder: A must be 2-D, got shape {R.shape}")
m, n = R.shape
k = min(m, n)
Q = np.eye(m)

Each step builds the unit reflector vv from the current sub-column:

for j in range(min(m - 1, n)): # the last row has nothing below it
x = R[j:, j]
norm_x = math.sqrt(float(x @ x))
if norm_x == 0.0:
continue # nothing below the diagonal to zero; avoids 0/0
# alpha has the opposite sign of x_0, so v_0 = x_0 - alpha never cancels.
# sign(0) is +1, hence alpha = -||x|| when x_0 == 0.
alpha = -math.copysign(norm_x, x[0]) if x[0] != 0.0 else -norm_x
v = x.copy() # x is a view into R; do not overwrite it
v[0] -= alpha # v = x - alpha e_1
v /= math.sqrt(float(v @ v)) # unit length, so H = I - 2 v v^T

Then it applies HjH_j to RR from the left and to QQ from the right, each as a rank-1 update:

R[j:, j:] -= 2.0 * np.outer(v, v @ R[j:, j:]) # R <- H R on the trailing block
Q[:, j:] -= 2.0 * np.outer(Q[:, j:] @ v, v) # Q <- Q H
R[j, j] = alpha
R[j + 1 :, j] = 0.0 # exact zeros, not rounding noise

Finally comes the reduction to kk columns and the sign rule. Multiplying Q by d scales its columns, and R * d[:, None] scales its rows, so QDDR=QRQDDR = QR:

Q, R = Q[:, :k], np.triu(R[:k, :])
d = np.where(np.diag(R) < 0.0, -1.0, 1.0) # zero diagonal counts as +1
return Q * d, R * d[:, None]

The initializer is a direct transcription of the recipe:

def orthogonal_init(shape: tuple[int, int], gain: float, rng: Any) -> NDArray:
rows, cols = int(shape[0]), int(shape[1])
if rows < 1 or cols < 1:
raise ValueError(f"orthogonal_init: shape must be positive, got {shape}")
G = normal(rng, rows * cols).reshape(rows, cols) # C order: reproducible from the seed
# QR gives orthonormal columns only for a tall input: factor G^T when wide.
Q, _ = qr_householder(G.T if rows < cols else G)
W = Q.T if rows < cols else Q
return gain * W # gain applied once

The full solution is qr.py.

Each step is two rank-1 updates, of an (m−j)×(n−j)(m - j) \times (n - j) and an m×(m−j)m \times (m - j) block, so factoring costs about 2mn2−23n32mn^2 - \frac{2}{3}n^3 flops for RR plus the work to accumulate the explicit QQ. Memory is O(m2+mn)O(m^2 + mn) because the full m×mm \times m QQ is accumulated and then truncated.

The alternatives each lose something. Gram-Schmidt, classical or modified, is cheaper to explain and produces QQ directly, but loses orthogonality in proportion to the condition number of AA; on the 101010^{10} case it is useless, while Householder’s loss is about ε\varepsilon regardless. Givens rotations also give an orthogonal QQ to working precision, but zero one entry at a time and cost about 1.5 times more on dense matrices; they win for sparse or banded matrices, which this book does not need here. np.linalg.qr would be faster, but its sign convention is LAPACK’s, and the point is to see where stability comes from; the sign rule makes the two comparable entry by entry anyway. The one tradeoff knowingly accepted is that accumulating the full m×mm \times m QQ is wasteful for a very tall matrix (LAPACK stores the reflectors instead), but it makes QQ trivially available to the initializer and to the QR algorithm in the next section.

The tests a correct solution passes follow the ideas above. The hand example must reproduce QQ and RR to 10−1510^{-15}, pinning the reflector and the sign rule. Random tall, wide, and square matrices must match np.linalg.qr entry by entry once the same sign rule is applied, which confirms the factorization is the unique one. A first column almost along e1e_1 must still give A=QRA = QR, which tests the reflector’s sign. A matrix with condition number about 101010^{10} must give Q⊤Q=IQ^\top Q = I to 10−1310^{-13}, which is the reason to use Householder and not Gram-Schmidt. Zero and dependent columns, which appear in singular weight matrices and padded inputs, must give finite, orthonormal, exact results. AA must be unchanged after the call, since the QR algorithm keeps iterating on its matrix, and a vector input must be rejected.

The initializer has its own checks. Across five shapes, W⊤W=g2IW^\top W = g^2 I or WW⊤=g2IWW^\top = g^2 I must hold, so every singular value equals the gain. The output must equal the sign-fixed QR of normal(rng, r * c) reshaped in C order, so that weights are reproducible from a seed. Over 400 seeds, W00>0W_{00} > 0 must hold about half the time, which is the Haar distribution showing through. And zero or negative dimensions must raise.

The mistakes that break those checks:

PitfallSymptomHow the solution avoids it
accumulating QQ from the wrong side (HQHQ instead of QHQH)QQ is orthogonal but QR≠AQR \ne Aupdates Q[:, j:] from the right
α=+sign⁡(x0)∥x∥\alpha = +\operatorname{sign}(x_0)\lVert x \rVertcatastrophic cancellation when a column is nearly along e1e_1alpha = -copysign(norm_x, x[0])
classical Gram-SchmidtQ⊤QQ^\top Q drifts far from II on ill-conditioned inputsuses reflections, never projections
normalizing a zero columndivision by zero, NaN everywhereskips a column with norm_x == 0.0
no sign rulefactors disagree with LAPACK’s; the initializer is biased (W00<0W_{00} < 0 every time)flips rows of RR and columns of QQ where diag(R) < 0
reducing the caller’s array in placethe next use of AA sees RRreduces np.array(A, dtype=np.float64), a copy
factoring a wide matrix without transposingrows are not orthonormalfactors G.T when rows < cols and transposes back
applying the gain twice (or squared)every weight scaled by g2g^2multiplies by gain once, at the end

Warning: Accumulating QQ from the wrong side is especially sneaky, because the result is still orthogonal and passes every Q⊤Q=IQ^\top Q = I check. Always test QR=AQR = A as well.

The next section, Eigenvalues, power iteration, and the spectral radius, runs the QR algorithm, At+1=RtQtA_{t+1} = R_t Q_t, with qr_householder to compute the spectral radius. SVD, Eckart-Young low rank, and least squares solves least squares min⁡∥Ax−b∥\min \lVert Ax - b \rVert by solving Rx=Q⊤bRx = Q^\top b. In AI Engineering, orthogonal_init is one of the default initializers of Linear in Module system and basic layers; recurrent weights in Vanilla RNN with manual BPTT and truncation and LSTM start orthogonal, so the hidden state neither explodes nor vanishes at step 0; and GRU and RNN language model with stateful TBPTT reuse it for their weights.

  • LAPACK dgeqrf and dorgqr (SRC/dgeqrf.f, dlarft.f): store reflectors compactly below RR and apply blocks of them as I−VTV⊤I - VTV^\top (the WY form) with matrix-matrix products.
  • numpy.linalg.qr(mode="reduced") (numpy/linalg/_linalg.py): returns QQ only when asked; least squares never forms it.
  • torch.nn.init.orthogonal_ (torch/nn/init.py): the same recipe on any tensor shape, flattened to 2-D.
  • Tall-skinny QR (TSQR): QR of row blocks combined in a tree, for distributed and GPU settings; Demmel et al., “Communication-optimal parallel and sequential QR” (2012).
  • Trefethen and Bau, Numerical Linear Algebra, lectures 7 to 10 (QR, Gram-Schmidt, Householder).
  • Saxe, McClelland, and Ganguli, “Exact solutions to the nonlinear dynamics of learning in deep linear neural networks” (2014).
  • Mezzadri, “How to generate random matrices from the classical compact groups” (2007).
  • Orthonormal: a set of unit-length vectors that are pairwise orthogonal.
  • Orthogonal matrix: a square QQ with Q⊤Q=IQ^\top Q = I; its inverse is its transpose.
  • Householder reflection: H=I−2vv⊤H = I - 2vv^\top with ∥v∥=1\lVert v \rVert = 1, which maps vv to −v-v and fixes the hyperplane orthogonal to vv.
  • Reduced QR: A=QRA = QR with QQ of shape (m,k)(m, k) and RR of shape (k,n)(k, n), k=min⁡(m,n)k = \min(m, n).
  • Sign rule: flipping signs so that diag⁡(R)≥0\operatorname{diag}(R) \ge 0, which makes the factorization unique.
  • Haar measure: the uniform distribution over orthogonal matrices.
  • A matrix QQ with orthonormal columns (Q⊤Q=IQ^\top Q = I) preserves lengths and angles; multiplying by it can neither blow up nor shrink a signal.
  • Householder QR zeroes each column below the diagonal with a reflection H=I−2vv⊤H = I - 2vv^\top; reflections are orthogonal by construction, so QQ stays orthogonal to machine precision even when Gram-Schmidt does not.
  • The reflector must send xx to −sign⁡(x0)∥x∥e1-\operatorname{sign}(x_0)\lVert x \rVert e_1; the other sign cancels catastrophically.
  • Requiring diag⁡(R)≥0\operatorname{diag}(R) \ge 0 makes the factorization unique, so it can be compared with LAPACK entry by entry, and makes orthogonal initialization uniformly distributed.
  • An orthogonal initializer is the sign-fixed QR of a Gaussian matrix (transposed when wide) times the gain, so every singular value equals the gain.
  1. Why is α\alpha chosen with the sign opposite to x0x_0?

    Answer

    The first entry of vv is x0−αx_0 - \alpha. With opposite signs it is x0+sign⁡(x0)∥x∥x_0 + \operatorname{sign}(x_0)\lVert x\rVert, a sum of two same-sign numbers, which is never smaller than ∥x∥\lVert x\rVert. With the same sign it is a difference that can round to zero when xx is nearly along e1e_1, and vv then points in a direction made of rounding error.

  2. Why is Q updated as Q[:, j:] -= 2 * outer(Q[:, j:] @ v, v) and not by multiplying HH on the left?

    Answer

    Hk−1⋯H0A=RH_{k-1} \cdots H_0 A = R, so A=H0⋯Hk−1RA = H_0 \cdots H_{k-1} R (each HH is its own inverse). QQ is that product in that order, which means each new reflector multiplies on the right. Multiplying on the left accumulates Hk−1⋯H0=Q⊤H_{k-1} \cdots H_0 = Q^\top instead: still orthogonal, but Q⊤R≠AQ^\top R \ne A in general.

  3. Without the sign rule, why would orthogonal_init have W00<0W_{00} < 0 every time?

    Answer

    The first reflector sets R00=α=−sign⁡(G00)∥G:,0∥R_{00} = \alpha = -\operatorname{sign}(G_{00})\lVert G_{:,0}\rVert, and Q00=G00/R00Q_{00} = G_{00}/R_{00}, which is then always negative. The sign rule makes R00>0R_{00} > 0, so Q00=G00/∥G:,0∥Q_{00} = G_{00}/\lVert G_{:,0}\rVert has the sign of G00G_{00}, positive half the time.

  4. Why does the loop run min(m - 1, n) times and not n times?

    Answer

    A reflector is needed only where there are entries below the diagonal. For a square matrix the last column has none, and for a wide matrix columns mm onward have no diagonal entry at all; the sign rule still fixes the last diagonal sign.

  5. Why does a wide (2,5)(2, 5) initializer factor G⊤G^\top?

    Answer

    QR of a 2×52 \times 5 matrix gives a 2×22 \times 2 QQ, which carries no information about the 5-dimensional rows. Factoring the 5×25 \times 2 transpose gives a 5×25 \times 2 QQ with orthonormal columns; its transpose is a 2×52 \times 5 matrix with orthonormal rows, which is what WW⊤=g2IWW^\top = g^2 I requires.