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 at every one of hundreds of steps. If stretches some direction by 1.1, that direction grows by ; if it shrinks one by 0.9, the gradient along it falls to . 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.
- Power iteration: repeated multiplication and normalization, converging to the dominant eigenvector. Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Unit roundoff: , the largest relative error of a single round-to-nearest. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- Standard normal: the distribution with density . Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Normal distribution / Gaussian distribution: the bell-shaped density with mean and variance ; about 68%, 95%, and 99.7% of its mass lies within one, two, and three standard deviations of the mean, and the central limit theorem makes it the limit of sample means. Read more: Chapter 13: Probability and Statistics
- QR algorithm: the iteration , converging to block upper triangular (real Schur) form. Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Catastrophic cancellation: losing most significant digits by subtracting two nearly equal rounded numbers. Read more: 6.4 Polynomials, Horner’s rule, and stable quadratic roots
- Spectral radius: . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
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 by reflections with , 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_householderandorthogonal_initand test them against LAPACK.
Notation
Section titled “Notation”These symbols recur through the section:
| Symbol | Meaning | Type / shape |
|---|---|---|
| inner (dot) product | scalar | |
| Euclidean length | scalar | |
| the matrix to factor, rows and columns | float64[m, n] | |
| the number of columns of in the reduced factorization | int | |
| orthonormal columns: | float64[m, k] | |
| upper triangular, non-negative diagonal | float64[k, n] | |
| vector | ||
| a unit vector defining a reflection | vector | |
| the Householder reflection across the hyperplane orthogonal to | square matrix | |
| the value a reflected column keeps in its first entry | scalar | |
| the gain of the initializer | scalar | |
| float64 unit roundoff, about |
Orthogonality
Section titled “Orthogonality”Two vectors are orthogonal when ; a set of vectors is orthonormal when every pair is orthogonal and each has length 1. A matrix whose columns are orthonormal satisfies , because entry of is . Then
preserves lengths and angles: multiplying by it can neither blow up nor shrink a signal. A square with is an orthogonal matrix; its inverse is its transpose, and its columns and rows are both orthonormal.
QR, and why reflections
Section titled “QR, and why reflections”Every real matrix with factors as , with having orthonormal columns and upper triangular. The first columns of span the first columns of , and 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 ‘s and normalizes. In floating point it computes the projections with rounding errors, and when two columns are nearly parallel (condition number ), what is left after subtracting is mostly those errors: the computed ‘s are far from orthogonal.
Householder takes the other route. It applies orthogonal matrices to until it becomes triangular, , so . Each with is a reflection: it maps to and leaves every vector orthogonal to alone. It is symmetric and its own inverse (), hence orthogonal. Since is a product of exactly orthogonal matrices, rounding errors only perturb it slightly: stays near whatever the conditioning of .
Choosing the reflector
Section titled “Choosing the reflector”That settles the strategy. The remaining question is which reflection to use at each step. Step looks at $x = $ column of the working matrix from row down, and wants a reflection that maps to , zeroing everything below the diagonal. Reflections preserve length, so , and the reflection that swaps and has along their difference:
Either sign of works in exact arithmetic. In floating point, the first entry of is , and if has the same sign as and is already almost along , this subtracts two nearly equal numbers and leaves only rounding error. With , , which rounds to exactly 1, so and points the wrong way. The fix is to choose , with . Then adds two numbers of the same sign and never cancels. If the column is already zero and the step is skipped.
Applying never forms the matrix: costs one product and one outer product. The solution applies it to the trailing block of (columns onward) and accumulates as on columns onward, then writes and exact zeros into column .
The sign rule and uniqueness
Section titled “The sign rule and uniqueness”QR as described is not quite unique. If , then also for any diagonal of ‘s, since . Fixing 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: where , else ; then and . 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 () gives : is square and is , upper trapezoidal. A tall one gives .
Orthogonal initialization
Section titled “Orthogonal initialization”With a unique, stable QR in hand, the initializer is a short recipe. torch.nn.init.orthogonal_ builds a weight of shape like this: draw with independent standard normal entries; if , factor instead; take from QR with the sign rule; transpose back if needed; multiply by the gain . The result has orthonormal columns (tall) or rows (wide), scaled by , so every singular value equals and (or ).
The sign rule is what makes uniformly distributed over orthogonal matrices (the Haar measure). The Gaussian distribution of is unchanged by any orthogonal transformation, so the distribution of would be too, except that the factorization’s own sign convention couples ‘s signs to ‘s. With this section’s reflector convention, always has the opposite sign of , so without the rule would be negative every single time. With the rule, is positive exactly half the time (Mezzadri 2007).
The draw is also deterministic: is normal(rng, r * c) reshaped in C order, so the same generator state gives the same weights in every run.
Working it by hand
Section titled “Working it by hand”Factor
One reflector suffices (), since a matrix has one entry below the diagonal. The table walks through it quantity by quantity:
| Quantity | Value |
|---|---|
| = column 0 | , |
| , length | |
| column 0 | |
| column 1 |
So and . The sign rule flips row 0 of and column 0 of (only is negative):
Check: , and the columns of are orthonormal: , .
Designing the API
Section titled “Designing the API”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.
Building it step by step
Section titled “Building it step by step”The reasoning chain is short. must be orthogonal to working precision whatever 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 . So the algorithm is: for each column, reflect the part on and below the diagonal onto a multiple of . The reflection must not cancel, which fixes with ; in the worked example gives and .
is never formed: costs instead of a full matrix product. It is applied to R[j:, j:] only, since rows above are not touched by and columns left of are already zero below the diagonal. Because , is accumulated by multiplying on the right, , and since is the identity outside rows and columns 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 onward have no diagonal entry at all. A zero sub-column is already done and is skipped, which avoids . The reduced factorization keeps the first columns of and rows of , 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 is factored as and the transposed back.
Set up a working copy that becomes , and an identity that becomes :
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 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^TThen it applies to from the left and to 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 noiseFinally comes the reduction to columns and the sign rule. Multiplying Q by d scales its columns, and R * d[:, None] scales its rows, so :
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 onceThe full solution is qr.py.
Why this design
Section titled “Why this design”Each step is two rank-1 updates, of an and an block, so factoring costs about flops for plus the work to accumulate the explicit . Memory is because the full is accumulated and then truncated.
The alternatives each lose something. Gram-Schmidt, classical or modified, is cheaper to explain and produces directly, but loses orthogonality in proportion to the condition number of ; on the case it is useless, while Householder’s loss is about regardless. Givens rotations also give an orthogonal 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 is wasteful for a very tall matrix (LAPACK stores the reflectors instead), but it makes trivially available to the initializer and to the QR algorithm in the next section.
What can go wrong
Section titled “What can go wrong”The tests a correct solution passes follow the ideas above. The hand example must reproduce and to , 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 must still give , which tests the reflector’s sign. A matrix with condition number about must give to , 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. 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, or 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, 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:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| accumulating from the wrong side ( instead of ) | is orthogonal but | updates Q[:, j:] from the right |
| catastrophic cancellation when a column is nearly along | alpha = -copysign(norm_x, x[0]) | |
| classical Gram-Schmidt | drifts far from on ill-conditioned inputs | uses reflections, never projections |
| normalizing a zero column | division by zero, NaN everywhere | skips a column with norm_x == 0.0 |
| no sign rule | factors disagree with LAPACK’s; the initializer is biased ( every time) | flips rows of and columns of where diag(R) < 0 |
| reducing the caller’s array in place | the next use of sees | reduces np.array(A, dtype=np.float64), a copy |
| factoring a wide matrix without transposing | rows are not orthonormal | factors G.T when rows < cols and transposes back |
| applying the gain twice (or squared) | every weight scaled by | multiplies by gain once, at the end |
Warning: Accumulating from the wrong side is especially sneaky, because the result is still orthogonal and passes every check. Always test as well.
Where this leads
Section titled “Where this leads”The next section, Eigenvalues, power iteration, and the spectral radius, runs the QR algorithm, , with qr_householder to compute the spectral radius. SVD, Eckart-Young low rank, and least squares solves least squares by solving . 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.
Further reading
Section titled “Further reading”- LAPACK
dgeqrfanddorgqr(SRC/dgeqrf.f,dlarft.f): store reflectors compactly below and apply blocks of them as (the WY form) with matrix-matrix products. numpy.linalg.qr(mode="reduced")(numpy/linalg/_linalg.py): returns 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).
Key terms
Section titled “Key terms”- Orthonormal: a set of unit-length vectors that are pairwise orthogonal.
- Orthogonal matrix: a square with ; its inverse is its transpose.
- Householder reflection: with , which maps to and fixes the hyperplane orthogonal to .
- Reduced QR: with of shape and of shape , .
- Sign rule: flipping signs so that , which makes the factorization unique.
- Haar measure: the uniform distribution over orthogonal matrices.
Summary
Section titled “Summary”- A matrix with orthonormal columns () 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 ; reflections are orthogonal by construction, so stays orthogonal to machine precision even when Gram-Schmidt does not.
- The reflector must send to ; the other sign cancels catastrophically.
- Requiring 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.
Review questions
Section titled “Review questions”-
Why is chosen with the sign opposite to ?
Answer
The first entry of is . With opposite signs it is , a sum of two same-sign numbers, which is never smaller than . With the same sign it is a difference that can round to zero when is nearly along , and then points in a direction made of rounding error.
-
Why is
Qupdated asQ[:, j:] -= 2 * outer(Q[:, j:] @ v, v)and not by multiplying on the left?Answer
, so (each is its own inverse). is that product in that order, which means each new reflector multiplies on the right. Multiplying on the left accumulates instead: still orthogonal, but in general.
-
Without the sign rule, why would
orthogonal_inithave every time?Answer
The first reflector sets , and , which is then always negative. The sign rule makes , so has the sign of , positive half the time.
-
Why does the loop run
min(m - 1, n)times and notntimes?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 onward have no diagonal entry at all; the sign rule still fixes the last diagonal sign.
-
Why does a wide initializer factor ?
Answer
QR of a matrix gives a , which carries no information about the 5-dimensional rows. Factoring the transpose gives a with orthonormal columns; its transpose is a matrix with orthonormal rows, which is what requires.