Householder and trainable orthogonals
Products of Householder reflections and the Cayley map, orthogonal for every value of their parameters
01 · Householder and trainable orthogonals¶
Notebook 00 fitted a rotation once (PCA, random or ICA) and froze it. Inside a parametric Gaussianization flow we want to learn the rotation by gradient descent, together with the marginal maps. A rotation must satisfy , and a general matrix updated by gradient descent does not stay orthogonal. We need a parameterisation, a smooth map from free parameters to a matrix , that is orthogonal for every . Then the rotation is free in the log-determinant (2) at every step of training, with no constraint and no projection.
gauss_flows ships two: HouseholderRotation, a product of Householder reflections, and OrthogonalRotation, the Cayley map of a skew-symmetric matrix.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
repo = "git+https://github.com/jejjohnson/gauss_flows@main"
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
f"gauss-flows-maps @ {repo}#subdirectory=packages/gauss-flows-maps",
f"gauss-flows-models @ {repo}#subdirectory=packages/gauss-flows-models",
f"gauss-flows-docs[notebooks] @ {repo}#subdirectory=docs",
],
check=True,
)import warnings
from collections.abc import Callable
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jr
import jax.scipy.linalg as jsl
import matplotlib.pyplot as plt
import numpy as np
import optax
from jaxtyping import ArrayLike, Float
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
GAUSS_KW,
LATENT_COLOR,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import HouseholderRotation, OrthogonalRotation
# Orthogonality checks get float64.
jax.config.update("jax_enable_x64", True)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "equinox", "optax", "matplotlib", "gauss_flows_maps")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
equinox : 0.13.8
optax : 0.2.8
matplotlib : 3.11.2
gauss_flows_maps: 0.3.0
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
1. The Householder reflection¶
Given a nonzero vector , the Householder reflection
mirrors every point across the hyperplane through the origin orthogonal to . It is orthogonal, it is its own inverse (), and it has , because it flips the one direction and keeps the directions orthogonal to it. We build one by hand in two dimensions.
# Shapes: state (D_x) = 2
StateMatrix = Float[ArrayLike, "state state"]
# user
# H(u) = I − 2 u uᵀ / (uᵀ u)
def householder(vector: Float[ArrayLike, " state"]) -> StateMatrix:
"""The Householder reflection across the hyperplane orthogonal to ``vector``."""
# u / ‖u‖, (state)
unit: Float[ArrayLike, " state"] = vector / jnp.linalg.norm(vector)
# I − 2 û ûᵀ, (state, state)
return jnp.eye(unit.shape[0]) - 2.0 * jnp.outer(unit, unit)We reflect across the line orthogonal to and check the three properties.
# user
# H(u) for u = (1, 1), (state, state)
reflection: StateMatrix = householder(jnp.array([1.0, 1.0]))
# max |HᵀH − I|
orthogonality_gap: float = jnp.max(jnp.abs(reflection.T @ reflection - jnp.eye(2)))
# max |H H − I|
involution_gap: float = jnp.max(jnp.abs(reflection @ reflection - jnp.eye(2)))
# det H
reflection_det: float = jnp.linalg.det(reflection)
print(f"max |H^T H - I| = {orthogonality_gap:.1e}")
print(f"max |H H - I| = {involution_gap:.1e}")
print(f"det H = {reflection_det:+.3f}")max |H^T H - I| = 4.4e-16
max |H H - I| = 4.4e-16
det H = -1.000
To see it act, we reflect the six corners of a letter F, which has no mirror symmetry of its own.
# Shapes: test = 6 corners of the letter
# the corners of an F, one per row, (test, state)
letter: Float[ArrayLike, "test state"] = np.array(
[[0, 0], [0, 2], [1, 2], [0, 2], [0, 1], [0.7, 1]], dtype=float
)
# H x for each corner, (test, state)
mirrored: Float[ArrayLike, "test state"] = letter @ reflection.Tfig, ax = plt.subplots(figsize=(4.5, 4.5))
ax.plot(letter[:, 0], letter[:, 1], "o-", color=DATA_COLOR, lw=2, label=r"$\mathbf{x}$")
ax.plot(
mirrored[:, 0],
mirrored[:, 1],
"o-",
color=LATENT_COLOR,
lw=2,
label=r"$\mathbf{H} \mathbf{x}$",
)
ax.plot([-2.5, 2.5], [2.5, -2.5], **GAUSS_KW, label="mirror line")
ax.annotate(
"",
xy=(0.9, 0.9),
xytext=(0, 0),
arrowprops={"arrowstyle": "->", "color": "C2", "lw": 2},
)
ax.text(0.95, 0.7, r"$\mathbf{v}$", color="C2", fontsize=13)
ax.set(xlabel="$x_1$", ylabel="$x_2$", xlim=(-2.5, 2.5), ylim=(-2.5, 2.5))
ax.set_aspect("equal")
ax.legend(fontsize=8, loc="lower right")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:The Householder reflection across the line orthogonal to (dashed) sends the letter F to its mirror image, which no rotation can produce.
2. Products of reflections¶
One reflection is not much, but every orthogonal matrix in dimensions is a product of at most reflections; this is the Cartan–Dieudonné theorem, and it is what the Householder QR factorisation computes. A product of reflections
is orthogonal for any vectors , and its determinant is fixed by the parity of ,
so an even gives a rotation and an odd a reflection. HouseholderRotation(n_reflections=K, shape=(D_x,)) is (2) with the vectors as its parameters, the Householder flow of Tomczak & Welling (2016). It applies one event at a time, so we read its matrix back column by column, .
# Shapes: state (D_x) = 3; latent (D_x) = 3
LatentState = Float[ArrayLike, "latent state"]
# user
# Q = [Q e₁, …, Q e_D], from the layer's action on the basis vectors
def matrix_of(layer) -> LatentState:
"""The matrix of a linear ``gauss_flows`` layer on ``(D_x,)`` events."""
# today (gauss_flows)
# Q eⱼ for each basis vector, as rows, (state, latent)
images: Float[ArrayLike, "state latent"] = jax.vmap(layer.transform)(jnp.eye(3))
return images.TFor we check the determinant against (3), the orthogonality, and how far the freshly built layer is from the identity.
for n_reflections in range(1, 5):
# today (gauss_flows)
# Q = H(v_K) … H(v₁) at its initial parameters
layer = HouseholderRotation(n_reflections=n_reflections, shape=(3,))
# user
# the layer's matrix, (latent, state)
matrix: LatentState = matrix_of(layer)
# max |QᵀQ − I|
gap: float = jnp.max(jnp.abs(matrix.T @ matrix - jnp.eye(3)))
# max |Q − I|
from_identity: float = jnp.max(jnp.abs(matrix - jnp.eye(3)))
print(
f"K = {n_reflections}: det Q = {jnp.linalg.det(matrix):+.2f}, "
f"max |Q^T Q - I| = {gap:.0e}, max |Q - I| = {from_identity:.2f}"
)K = 1: det Q = -1.00, max |Q^T Q - I| = 6e-16, max |Q - I| = 1.09
K = 2: det Q = +1.00, max |Q^T Q - I| = 9e-16, max |Q - I| = 0.00
K = 3: det Q = -1.00, max |Q^T Q - I| = 1e-15, max |Q - I| = 1.09
K = 4: det Q = +1.00, max |Q^T Q - I| = 2e-15, max |Q - I| = 0.00
The determinant follows and every product is orthogonal to machine precision. The initial layer is the identity for even and a single reflection for odd , because HouseholderRotation starts all vectors equal, and two equal reflections cancel. An even is therefore the natural choice for a flow layer: it starts as the identity, and it is a rotation for every value of its parameters.
3. Training a rotation¶
The parameters of (2) are unconstrained, so we can train them with any optimiser and stays orthogonal. We show it by fitting a target rotation , minimising
with Adam, where the equality holds for any two orthogonal matrices. As a baseline we train a general matrix the same way. gauss_flows returns a log-determinant of exactly zero for its orthogonal layers, by construction rather than by computation, so what we track during training is the orthogonality of , the property that makes that zero correct.
The target is a random rotation: the factor of the QR factorisation of a Gaussian matrix (5), with one column flipped when its determinant has the wrong sign.
# user
# Q⋆ from G = Q R, with det Q⋆ = sign, (latent, state)
def random_orthogonal(key: jax.Array, sign: float) -> LatentState:
"""A random orthogonal matrix with determinant ``sign``."""
# G = Q R for a Gaussian G, (latent, state)
target: LatentState
target, _ = jnp.linalg.qr(jr.normal(key, (3, 3)))
# flip the first column if det Q has the wrong sign, (latent, state), (state)
flip: Float[ArrayLike, " state"] = jnp.array(
[jnp.sign(jnp.linalg.det(target)) * sign, 1.0, 1.0]
)
return target * flip
# user
# a random rotation, det Q⋆ = +1, (latent, state)
target_rotation: LatentState = random_orthogonal(jr.key(1), +1.0)The fitting loop takes any layer with a transform method, so it serves the Householder layer, the Cayley layer and the general matrix alike. It records the fit (4) and the orthogonality gap at every step.
# Shapes: step = 1,500 Adam steps
PerStep = Float[ArrayLike, " step"]
# user
# ‖Q(θ) − Q⋆‖²_F
def fit_loss(params, static, target: LatentState) -> float:
"""The squared Frobenius distance between the layer's matrix and ``target``."""
# user
# Q(θ), (latent, state)
matrix: LatentState = matrix_of(eqx.combine(params, static))
return jnp.sum((matrix - target) ** 2)# user
# Adam on ‖Q(θ) − Q⋆‖²_F, recording the fit and max |QᵀQ − I| at each step
def fit(layer, target: LatentState) -> tuple[PerStep, PerStep, eqx.Module]:
"""Fit ``layer``'s matrix to ``target``; return the two histories and the trained layer."""
params: eqx.Module
static: eqx.Module
# today (equinox)
# θ, the trainable arrays, and the fixed rest of the layer
params, static = eqx.partition(layer, eqx.is_inexact_array)
# today (optax)
# Adam with step size 0.05
optimiser: optax.GradientTransformation = optax.adam(5e-2)
# today (optax)
# Adam's moment estimates, at zero
state: optax.OptState = optimiser.init(params)
fits, gaps = [], []
for _ in range(1500):
loss: float
# user
# one Adam step on ‖Q(θ) − Q⋆‖²_F
params, state, loss = adam_step(params, state, static, target, optimiser)
# user
# Q(θ) after the step, (latent, state)
matrix: LatentState = matrix_of(eqx.combine(params, static))
fits.append(loss)
gaps.append(jnp.max(jnp.abs(matrix.T @ matrix - jnp.eye(3))))
return np.array(fits), np.array(gaps), eqx.combine(params, static)One Adam step is a gradient of (4) and an update, compiled once.
# user
# θ ← θ − Adam(∇_θ ‖Q(θ) − Q⋆‖²_F)
def step(params, state, static, target: LatentState, optimiser):
"""One Adam step on the fit."""
loss: float
gradient: eqx.Module
# user
# ‖Q(θ) − Q⋆‖²_F and its gradient
loss, gradient = jax.value_and_grad(fit_loss)(params, static, target)
update: eqx.Module
state: optax.OptState
# today (optax)
# the Adam update
update, state = optimiser.update(gradient, state)
# today (optax)
# θ ← θ + update
return optax.apply_updates(params, update), state, loss
# today (equinox)
# the step, compiled once per layer type
adam_step: Callable = eqx.filter_jit(step)The general matrix is the identity to start with, like the Householder layer with .
# user
# z = M x for an unconstrained M
class GeneralMatrix(eqx.Module):
"""A general linear map, with no constraint on its matrix."""
weights: LatentState
# user
# z = M x, (latent)
def transform(
self, point: Float[ArrayLike, " state"]
) -> Float[ArrayLike, " latent"]:
"""Apply the matrix to one event."""
return self.weights @ pointWe fit both to the target rotation.
# user
# K = 2 reflections fitted to Q⋆, (step), (step), (step)
householder_fit: PerStep
householder_gap: PerStep
householder_fit, householder_gap, _ = fit(
HouseholderRotation(n_reflections=2, shape=(3,)), target_rotation
)
# user
# a general matrix fitted to Q⋆, (step), (step), (step)
general_fit: PerStep
general_gap: PerStep
general_fit, general_gap, _ = fit(GeneralMatrix(jnp.eye(3)), target_rotation)
print(
f"Householder (K = 2): final fit {householder_fit[-1]:.1e}, max |Q^T Q - I| over training {householder_gap.max():.1e}"
)
print(
f"general matrix : final fit {general_fit[-1]:.1e}, max |M^T M - I| over training {general_gap.max():.2f}"
)Householder (K = 2): final fit 5.3e-32, max |Q^T Q - I| over training 1.3e-15
general matrix : final fit 1.2e-32, max |M^T M - I| over training 0.55
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].semilogy(householder_fit, color="C4", lw=2, label="Householder, $K = 2$")
axes[0].semilogy(general_fit, color="C7", lw=2, label="general matrix")
axes[0].set(
xlabel="step",
ylabel=r"$\Vert \mathbf{Q}(\theta) - \mathbf{Q}_\star \Vert_F^2$",
title="Fit",
)
axes[1].semilogy(householder_gap, color="C4", lw=2, label="Householder, $K = 2$")
axes[1].semilogy(general_gap, color="C7", lw=2, label="general matrix")
axes[1].set(
xlabel="step",
ylabel=r"$\max \vert \mathbf{Q}^\top \mathbf{Q} - \mathbf{I} \vert$",
title="Orthogonality",
)
for ax in axes:
ax.legend(fontsize=8)
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:Fitting a random rotation with Adam. Left: both layers reach the target to machine precision. Right: the Householder layer stays orthogonal at every step, while the general matrix leaves the orthogonal group on the way and its log-determinant is no longer zero there.
Both fits reach machine precision. The Householder layer is orthogonal to about 10-15 at every one of the 1,500 steps, while the general matrix wanders up to about 0.55 away from orthogonality before it settles. Inside a flow that general matrix would have to pay its log-determinant at every step, and nothing would stop it from drifting towards a singular matrix.
4. The Cayley map and the matrix exponential¶
The other route starts from a skew-symmetric matrix , which has free entries. Two maps send it to an orthogonal matrix, the Cayley map
and the matrix exponential
Both give , so both produce rotations only, and both give the identity at . OrthogonalRotation is the Cayley map, with the strictly lower triangle of as its parameters and at the start; it costs one linear solve per evaluation. We check both maps on a random , then train OrthogonalRotation on the same target.
# Shapes: pair = 3 entries below the diagonal
# the free entries of S, (pair)
lower_entries: Float[ArrayLike, " pair"] = jr.normal(jr.key(7), (3,))
# the strictly lower triangle of S, (state, state)
lower: StateMatrix = jnp.zeros((3, 3)).at[jnp.tril_indices(3, -1)].set(lower_entries)
# S = L − Lᵀ, (state, state)
skew: StateMatrix = lower - lower.T
# Q = (I − S)(I + S)⁻¹, (latent, state)
cayley: LatentState = (jnp.eye(3) - skew) @ jnp.linalg.inv(jnp.eye(3) + skew)
# Q = exp(S), (latent, state)
exponential: LatentState = jsl.expm(skew)for name, matrix in [("Cayley", cayley), ("exp", exponential)]:
# max |QᵀQ − I|
gap: float = jnp.max(jnp.abs(matrix.T @ matrix - jnp.eye(3)))
print(
f"{name:6s}: max |Q^T Q - I| = {gap:.0e}, det Q = {jnp.linalg.det(matrix):+.3f}"
)
# user
# OrthogonalRotation fitted to Q⋆, (step), (step), (step)
cayley_fit: PerStep
cayley_gap: PerStep
cayley_fit, cayley_gap, _ = fit(OrthogonalRotation(shape=(3,)), target_rotation)
print(
f"OrthogonalRotation: final fit {cayley_fit[-1]:.1e}, max |Q^T Q - I| over training {cayley_gap.max():.1e}"
)Cayley: max |Q^T Q - I| = 2e-16, det Q = +1.000
exp : max |Q^T Q - I| = 2e-16, det Q = +1.000
OrthogonalRotation: final fit 6.2e-22, max |Q^T Q - I| over training 6.7e-16
Both maps are orthogonal to machine precision with determinant +1, and OrthogonalRotation fits the target rotation as well as the Householder layer did. For a rotation target the two layers are interchangeable; they differ in what they can reach.
5. What each can reach¶
A product of reflections with the wrong parity, or the Cayley map, can never produce a matrix of the other determinant. For two orthogonal matrices of opposite determinant, has determinant -1, so at least one of its eigenvalues is -1, its trace is at most , and by (4)
whatever is. A fit across the determinant stalls at 4.
The Cayley map has a second gap. The eigenvalues of a skew-symmetric are imaginary, , so those of (5) are , which is never -1. The Cayley map therefore misses every rotation with an eigenvalue -1, such as the half-turn , and approaches it only as . The matrix exponential reaches it with .
We fit a random reflection () and the half-turn with each layer. The Cayley layer starts from a small random for the half-turn, because at the gradient towards a symmetric target such as a half-turn is exactly zero.
# user
# a random reflection, det Q⋆ = −1, (latent, state)
target_reflection: LatentState = random_orthogonal(jr.key(1), -1.0)
# the half-turn about the third axis, (latent, state)
half_turn: LatentState = jnp.diag(jnp.array([-1.0, -1.0, 1.0]))
# today (equinox)
# OrthogonalRotation with S set to small values
perturbed_cayley: OrthogonalRotation = eqx.tree_at(
lambda layer: layer.skew_params,
OrthogonalRotation(shape=(3,)),
jnp.array([0.1, 0.2, -0.1]),
)
# user
# exp(S) for S with ψ = π in the plane of the first two axes, (latent, state)
exponential_half_turn: LatentState = jsl.expm(
jnp.array([[0.0, -jnp.pi, 0.0], [jnp.pi, 0.0, 0.0], [0.0, 0.0, 0.0]])
)
print(
f"max |exp(S) - half-turn| = {jnp.max(jnp.abs(exponential_half_turn - half_turn)):.0e}"
)max |exp(S) - half-turn| = 1e-16
Now the four fits.
# today (gauss_flows)
# each layer with its target
runs = {
"Householder K = 3, reflection": (
HouseholderRotation(n_reflections=3, shape=(3,)),
target_reflection,
),
"Cayley, reflection": (OrthogonalRotation(shape=(3,)), target_reflection),
"Householder K = 2, half-turn": (
HouseholderRotation(n_reflections=2, shape=(3,)),
half_turn,
),
"Cayley, half-turn": (perturbed_cayley, half_turn),
}Each run keeps its fit history and its trained layer.
reach_fits, reach_layers = {}, {}
for name, (layer, target) in runs.items():
history: PerStep
trained: eqx.Module
# user
# the fit history and the trained layer, (step)
history, _, trained = fit(layer, target)
reach_fits[name] = history
reach_layers[name] = trained
print(f"{name:30s} final fit {reach_fits[name][-1]:.1e}")Householder K = 3, reflection final fit 1.0e-30
Cayley, reflection final fit 4.0e+00
Householder K = 2, half-turn final fit 9.9e-32
Cayley, half-turn final fit 9.7e-02
For the Cayley layer on the half-turn we also look at how large its parameters have grown.
# today (gauss_flows)
# the trained free entries of S, (pair)
half_turn_entries: Float[ArrayLike, " pair"] = reach_layers[
"Cayley, half-turn"
].skew_params
print(
f"Cayley on the half-turn: largest |S_ij| after 1,500 steps = {jnp.max(jnp.abs(half_turn_entries)):.1f}"
)Cayley on the half-turn: largest |S_ij| after 1,500 steps = 9.0
fig, ax = plt.subplots(figsize=(7, 4.2))
styles = {
"Householder K = 3, reflection": ("C4", "-"),
"Cayley, reflection": ("C1", "-"),
"Householder K = 2, half-turn": ("C4", "--"),
"Cayley, half-turn": ("C1", "--"),
}
for name, history in reach_fits.items():
color, line = styles[name]
ax.semilogy(np.maximum(history, 1e-32), color=color, ls=line, lw=2, label=name)
ax.axhline(4.0, color="k", lw=1, ls=":", label="bound 4 across the determinant")
ax.set(xlabel="step", ylabel=r"$\Vert \mathbf{Q}(\theta) - \mathbf{Q}_\star \Vert_F^2$")
ax.legend(fontsize=8)
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 3:Fits across the two gaps. A reflection target is reached by three Householder reflections, while the Cayley layer stalls at the bound 4 of the determinant. A half-turn is reached by two Householder reflections, while the Cayley layer creeps towards it as its parameters grow.
Three Householder reflections reach the reflection to machine precision and the Cayley layer stops at exactly 4, the bound (7); no amount of training can cross it. On the half-turn, two reflections are exact while the Cayley layer is still about 0.1 away after 1,500 steps, with an entry of near 9; the exponential map hits the half-turn with . Neither gap matters much for a Gaussianization flow, where the next marginal step can absorb a sign flip and a near half-turn is good enough, but they are why HouseholderRotation and OrthogonalRotation are not interchangeable in general.
Recap¶
| Idea | Equation | In code |
|---|---|---|
| one reflection | (1) | householder above |
| a product of reflections, | (2), (3) | HouseholderRotation(n_reflections=K, shape=(D_x,)) |
| fitting a target rotation | (4) | fit above, with optax.adam |
| the Cayley map, rotations only | (5) | OrthogonalRotation(shape=(D_x,)) |
| the matrix exponential, every rotation | (6) | jax.scipy.linalg.expm |
| the gap across the determinant | (7) | Figure 3 |
Next. Sometimes we do not want to learn the rotation at all, but to fix it from the data (a PCA frame) and learn only the marginals, or to start a trainable stack from a fitted rotation. The next notebook covers FixedRotation and warm starts.
- Tomczak, J. M., & Welling, M. (2016). Improving Variational Auto-Encoders using Householder Flow. NeurIPS Workshop on Bayesian Deep Learning.