Fixed rotations and warm starts
Freezing a PCA frame inside a flow, what goes wrong with a free matrix, and starting a trainable rotation at a given frame
02 · Fixed rotations and warm starts¶
Notebook 01 made the rotation trainable. Often the rotation we want is one we do not train: the PCA frame (3) decorrelates the data in one step (notebook 00), so a flow can fix that frame and spend its parameters on the marginals. When we do want a trainable rotation, we can start it at the PCA frame instead of at an arbitrary one. This notebook does both with gauss_flows.
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
warnings.filterwarnings("ignore", message=r".*IProgress.*")
from typing import ClassVar
import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
from flowjax.bijections import AbstractBijection, Affine, Chain, Invert
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Float
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import FixedRotation, HouseholderRotation
from gauss_flows_models.inference import fit_gaussianization_flow
from gauss_flows_models.info_theory import gaussian_entropy
# Log-determinants and round trips 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", "numpy", "matplotlib", "flowjax", "gauss_flows_maps", "gauss_flows_models"
)Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
matplotlib : 3.11.2
flowjax : 19.1.0
gauss_flows_maps : 0.3.0
gauss_flows_models: 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
Throughout, the data are draws of a correlated Gaussian in dimensions, , drawn as a fixed lower-triangular square root of times standard normal noise, with principal variances of about 5.7, 1.0 and 0.11.
# Shapes: sample (N) = 4,000; state (D_x) = 3
StateMatrix = Float[ArrayLike, "state state"]
# a lower-triangular square root of Σ_x, (state, state)
loadings: StateMatrix = jnp.array([[2.0, 0.0, 0.0], [1.2, 0.8, 0.0], [0.4, -0.6, 0.5]])
SampleState = Float[ArrayLike, "sample state"]
# standard normal noise, (sample, state)
noise: SampleState = jr.normal(jr.key(0), (4000, 3))
# x ~ 𝒩(0, Σ_x), the square root times the noise, (sample, state)
samples: SampleState = noise @ loadings.T1. The PCA frame as a fixed rotation¶
FixedRotation.from_data takes the eigenvectors of the sample covariance and stores the orthogonal matrix of (3), whose rows are the principal axes in order of decreasing variance. The rotated data are uncorrelated,
and since is orthogonal its log-determinant is zero (2). It does not rescale: the variances along the new axes are the diagonal of , still unequal, and standardising them is left to the marginal step that follows.
# today (gauss_flows)
# Q = Vᵀ from the eigenvectors of the sample covariance
pca_frame: FixedRotation = FixedRotation.from_data(samples)
# today (gauss_flows)
# Q, (state, state)
frame_matrix: StateMatrix = pca_frame.matrix
# today (gauss_flows)
# z = Q x for every sample, (sample, state)
rotated: SampleState = jax.vmap(pca_frame.transform)(samples)
# max |QᵀQ − I|
orthogonality_gap: float = jnp.max(jnp.abs(frame_matrix.T @ frame_matrix - jnp.eye(3)))We check the round trip and the log-determinant on one point, and the covariance before and after.
PerState = Float[ArrayLike, " state"]
# one test point, (state)
test_point: PerState = jr.normal(jr.key(1), (3,))
test_latent: PerState
test_logdet: float
# today (gauss_flows)
# z = Q x and log |det Q|
test_latent, test_logdet = pca_frame.transform_and_log_det(test_point)
test_back: PerState
# today (gauss_flows)
# x̂ = Qᵀ z
test_back, _ = pca_frame.inverse_and_log_det(test_latent)
# Σ_x from the samples, (state, state)
covariance_before: StateMatrix = np.cov(np.asarray(samples).T)
# Q Σ_x Qᵀ from the rotated samples, (state, state)
covariance_after: StateMatrix = np.cov(np.asarray(rotated).T)The largest off-diagonal entry of each covariance measures how correlated the coordinates are.
# user
# the largest off-diagonal entry of a covariance
def largest_off_diagonal(covariance: StateMatrix) -> float:
"""The largest absolute off-diagonal entry of ``covariance``."""
# Σ − diag(Σ), (state, state)
off_diagonal: StateMatrix = covariance - np.diag(np.diag(covariance))
return np.max(np.abs(off_diagonal))
print(f"max |Q^T Q - I| = {orthogonality_gap:.1e}")
print(
f"log|det Q| = {test_logdet:+.1e}, round trip {jnp.max(jnp.abs(test_point - test_back)):.1e}"
)
print(
f"largest off-diagonal covariance: before {largest_off_diagonal(covariance_before):.3f}, after {largest_off_diagonal(covariance_after):.1e}"
)
print(f"variances after: {np.round(np.diag(covariance_after), 3)}")max |Q^T Q - I| = 2.2e-16
log|det Q| = +0.0e+00, round trip 2.2e-16
largest off-diagonal covariance: before 2.428, after 3.2e-15
variances after: [5.771 1.029 0.112]
fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), sharex=True, sharey=True)
axes[0].scatter(samples[:, 0], samples[:, 1], color=DATA_COLOR, **SCATTER_KW)
axes[0].set(title="data", xlabel="$x_1$", ylabel="$x_2$")
axes[1].scatter(rotated[:, 0], rotated[:, 1], color=LATENT_COLOR, **SCATTER_KW)
axes[1].set(
title="PCA frame, $\\mathbf{z} = \\mathbf{Q} \\mathbf{x}$",
xlabel="$z_1$",
ylabel="$z_2$",
)
for ax in axes:
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:The first two coordinates of the data (left) and of the data in the PCA frame of FixedRotation.from_data (right). The frame lines the cloud up with the axes, so the coordinates are uncorrelated, but their variances still differ.
The rotation is orthogonal and exact to machine precision, the off-diagonal covariance drops from 2.4 to rounding error, and the variances along the new axes are the principal variances 5.7, 1.0 and 0.11.
2. Why the frame is frozen¶
FixedRotation stores its matrix wrapped in paramax.NonTrainable, and fit_gaussianization_flow trains only the floating-point leaves outside such wrappers, so the frame does not move. The alternative, a plain matrix that the optimiser may change while the flow still books its log-determinant as zero, as it would for a rotation, goes wrong in a specific way. With a standard normal base, the loss the flow reports is
while the true negative log-likelihood of the change of variables (5) also counts the volume change,
Minimising rewards shrinking the data towards the origin, where the base density is highest, and nothing stops it, because the term that would charge for the shrinking is missing. We write such a layer, start it at the PCA frame, and train it with fit_gaussianization_flow.
# user
# z = A x with a free matrix, its log-determinant booked as zero
class BookedAsRotation(AbstractBijection):
"""A free linear map that reports ``log_det = 0``, as a rotation would."""
# the event shape, (D_x,)
shape: tuple[int, ...]
# no condition
cond_shape: ClassVar[None] = None
# A, (state, state)
matrix: StateMatrix
# user
# z = A x, with log |det A| booked as 0
def transform_and_log_det(self, x, condition=None):
return self.matrix @ x, jnp.zeros(())
# user
# x = A⁻¹ z, with log |det A⁻¹| booked as 0
def inverse_and_log_det(self, y, condition=None):
return jnp.linalg.solve(self.matrix, y), jnp.zeros(())The flow’s density direction is , so the layer goes in inverted, as a flowjax Transformed maps the base to the data.
# user
# p_x(x) = 𝒩(A x; 0, I), with A = Q at the start
booked_flow: Transformed = Transformed(
StandardNormal((3,)), Invert(BookedAsRotation((3,), jnp.asarray(frame_matrix)))
)
# today (gauss_flows)
# minimise 𝓛₀(A) by Adam for 60 epochs
booked_trained: Transformed
booked_losses: dict[str, list[float]]
booked_trained, booked_losses = fit_gaussianization_flow(
jr.key(2),
booked_flow,
samples,
learning_rate=1e-2,
max_epochs=60,
show_progress=False,
)
# the trained A, (state, state)
trained_matrix: StateMatrix = booked_trained.bijection.bijection.matrixWe compare the loss the flow reports with the true one (3), and the trained matrix with a rotation.
# today (flowjax)
# 𝓛₀(A), the loss the flow reports
reported_nll: float = -jnp.mean(booked_trained.log_prob(samples))
# log |det A|
trained_logdet: float = jnp.linalg.slogdet(trained_matrix)[1]
# 𝓛(A) = 𝓛₀(A) − log |det A|
true_nll: float = reported_nll - trained_logdet
# max |AᵀA − I|
trained_gap: float = jnp.max(jnp.abs(trained_matrix.T @ trained_matrix - jnp.eye(3)))
# today (gauss_flows)
# ½ log det(2πe Σ_x), the best a Gaussian can do
gaussian_bound: float = gaussian_entropy(jnp.cov(samples.T, bias=True))
# today (flowjax)
# x = A⁻¹ z for 1,000 base draws, (sample, state)
booked_draws: SampleState = booked_trained.sample(jr.key(3), (1000,))
print(f"max |A^T A - I| = {trained_gap:.3f}, log|det A| = {trained_logdet:+.1f}")
print(
f"largest standard deviation of its samples: {jnp.max(jnp.std(booked_draws, axis=0)):.1e}"
)
print(
f"reported NLL {reported_nll:.3f}, true NLL {true_nll:.1f}, Gaussian bound {gaussian_bound:.3f}"
)max |A^T A - I| = 0.999, log|det A| = -58.8
largest standard deviation of its samples: 1.7e+19
reported NLL 2.757, true NLL 61.6, Gaussian bound 4.055
The matrix has shrunk almost to zero, with around -59. The flow reports a negative log-likelihood of about 2.76, better than any Gaussian can achieve on this data (the bound of section 4, about 4.06), while the true value is about 62. Sampling inverts , so its samples have standard deviations around 1019. Nothing in the reported loss flags the problem.
The same training leaves a FixedRotation exactly where it started. We put the PCA frame before a per-coordinate affine map, , which is a flow that can standardise the rotated coordinates, and train it.
# user
# z = diag(a) Q x + b, a flow on the rotation Q
def affine_after(rotation, shift: PerState, scale: PerState) -> Transformed:
"""The flow ``z = diag(scale) Q x + shift`` with a standard normal base."""
# today (flowjax)
# Q, then the per-coordinate affine map, in the density direction
return Transformed(
StandardNormal((3,)), Invert(Chain([rotation, Affine(shift, scale)]))
)Every flow in this notebook is trained the same way, with Adam until the held-out loss has not improved for five epochs, keeping the best epoch.
# user
# train a flow by maximum likelihood
def train(flow: Transformed) -> tuple[Transformed, list[float]]:
"""The trained flow and its held-out loss per epoch."""
# today (gauss_flows)
# minimise 𝓛 by Adam, keeping the best epoch
trained: Transformed
losses: dict[str, list[float]]
trained, losses = fit_gaussianization_flow(
jr.key(2),
flow,
samples,
learning_rate=1e-2,
max_epochs=300,
show_progress=False,
)
return trained, losses["val"]We train it with the frozen PCA frame, starting at and .
# user
# the flow with the frozen frame, trained
frozen_trained: Transformed
frozen_history: list[float]
frozen_trained, frozen_history = train(
affine_after(pca_frame, jnp.zeros(3), jnp.ones(3))
)
# today (flowjax)
# 𝓛 of the trained flow on all the data
frozen_nll: float = -jnp.mean(frozen_trained.log_prob(samples))
# the rotation after training, (state, state)
frozen_after: StateMatrix = frozen_trained.bijection.bijection.bijections[0].matrix
print(f"largest change in Q: {jnp.max(jnp.abs(frozen_after - frame_matrix)):.1e}")
print(
f"NLL {frozen_nll:.4f} after {len(frozen_history)} epochs, Gaussian bound {gaussian_bound:.4f}"
)largest change in Q: 0.0e+00
NLL 4.0546 after 51 epochs, Gaussian bound 4.0545
The frame did not change in a single bit, and the flow reaches the best Gaussian fit to four decimal places. A rotation inside a flow should either be frozen like this or parametrised so that every update stays orthogonal, as the Householder and Cayley layers of notebook 01 are. It should never be a plain matrix.
3. Starting a trainable rotation at a given frame¶
To train the rotation and still start at the PCA frame, we set the reflection vectors of a HouseholderRotation so that their product is . A Householder reflection can send any vector to a multiple of a coordinate axis, which is how QR factorisations are computed. Applied to the columns of one at a time, each reflection moves column onto the axis without disturbing the columns already placed, and since is orthogonal the reduction ends at the identity,
where a step whose column is already in place is skipped. Each reflection is its own inverse, so , at most reflections. HouseholderRotation applies its reflections in the order of its parameter rows, the first row first, so the rows are the vectors in reverse order.
# user
# the vectors u_d of H(u_D) … H(u_1) Q = I, in HouseholderRotation's order
def householder_vectors(rotation: StateMatrix) -> Float[ArrayLike, "reflection state"]:
"""Reflection vectors whose ``HouseholderRotation`` equals ``rotation``."""
# the matrix being reduced to I, (state, state)
reduced: StateMatrix = np.array(rotation, dtype=float)
vectors = []
for column in range(len(reduced)):
# e_d, the coordinate axis d, (state)
axis: PerState = np.eye(len(reduced))[column]
# x, column d from row d down, (state)
below: PerState = np.where(axis.cumsum() > 0, reduced[:, column], 0.0)
# u = x − ‖x‖ e_d, (state)
vector: PerState = below - np.linalg.norm(below) * axis
if np.linalg.norm(vector) > 1e-12:
# û = u / ‖u‖, (state)
vector = vector / np.linalg.norm(vector)
# H(û) applied to the partly reduced matrix, (state, state)
reduced = reduced - 2.0 * np.outer(vector, vector @ reduced)
vectors.append(vector)
return np.array(vectors[::-1])We decompose the PCA frame and put the vectors into a HouseholderRotation with eqx.tree_at.
# Shapes: reflection = 2 vectors for this frame
# user
# u_d for the PCA frame, (reflection, state)
reflections: Float[ArrayLike, "reflection state"] = householder_vectors(frame_matrix)
# today (gauss_flows)
# a HouseholderRotation with those vectors as its parameters
warm_rotation: HouseholderRotation = eqx.tree_at(
lambda layer: layer.params,
HouseholderRotation(n_reflections=len(reflections), shape=(3,)),
jnp.asarray(reflections),
)
# today (gauss_flows)
# its matrix, from the images of the basis vectors, (state, state)
warm_matrix: StateMatrix = jax.vmap(warm_rotation.transform)(jnp.eye(3)).T
print(
f"{len(reflections)} reflections, max |Q_warm - Q| = {jnp.max(jnp.abs(warm_matrix - frame_matrix)):.1e}"
)2 reflections, max |Q_warm - Q| = 2.2e-16
Two reflections suffice for this frame, and the trainable rotation reproduces it to machine precision.
4. Cold and warm starts under maximum likelihood¶
We train the flow again, now with a trainable HouseholderRotation for . For a fixed rotation the best per-coordinate affine map fits a Gaussian to each rotated coordinate, so the best loss is a sum of one-dimensional Gaussian entropies, and Hadamard’s inequality bounds it by the entropy (2) of the Gaussian fit to all the data,
with equality exactly when is diagonal (1). The PCA frame is therefore the rotation that maximum likelihood looks for. We compare three starts:
cold: the default
HouseholderRotation(n_reflections=3), with and ;warm rotation: the PCA frame of section 3, with and ;
warm layer: the PCA frame with and , which is PCA whitening, the solution itself.
The default HouseholderRotation repeats one vector in every row, so with an odd number of reflections it starts as a single reflection.
# today (gauss_flows)
# the default parameters, one row per reflection
print(HouseholderRotation(n_reflections=3, shape=(3,)).params)
# Λ, the variances along the PCA axes, (state)
principal_variances: PerState = jnp.var(rotated, axis=0)
# a = Λ^(−1/2), (state)
whitening_scale: PerState = 1.0 / jnp.sqrt(principal_variances)
# b = −Λ^(−1/2) Q x̄, (state)
whitening_shift: PerState = -whitening_scale * jnp.mean(rotated, axis=0)
# today (gauss_flows)
# the three starts: (Q, b, a)
starts = {
"cold": (
HouseholderRotation(n_reflections=3, shape=(3,)),
jnp.zeros(3),
jnp.ones(3),
),
"warm rotation": (warm_rotation, jnp.zeros(3), jnp.ones(3)),
"warm layer": (warm_rotation, whitening_shift, whitening_scale),
}[[1. 0.70710678 0.57735027]
[1. 0.70710678 0.57735027]
[1. 0.70710678 0.57735027]]
Each start is trained the same way, and we record the held-out loss of every epoch.
histories = {}
for name, start in starts.items():
# user
# train from this start
trained: Transformed
history: list[float]
trained, history = train(affine_after(*start))
# today (flowjax)
# 𝓛 of the trained flow on all the data
final_nll: float = -jnp.mean(trained.log_prob(samples))
histories[name] = history
print(
f"{name:13s} first epoch {history[0]:.3f}, {len(history):3d} epochs, final NLL {final_nll:.4f}"
)cold first epoch 5.736, 40 epochs, final NLL 4.0562
warm rotation first epoch 5.585, 44 epochs, final NLL 4.0559
warm layer first epoch 3.989, 7 epochs, final NLL 4.0553
fig, ax = plt.subplots(figsize=(7.5, 4.2))
for (name, history), color in zip(histories.items(), ["C0", "C2", "C3"], strict=True):
ax.plot(history, color=color, lw=2, label=name)
ax.axhline(gaussian_bound, color="k", lw=1.2, ls="--", label="Gaussian bound")
ax.set(xlabel="epoch", ylabel="held-out NLL (nats)", title="Cold and warm starts")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:Held-out negative log-likelihood per epoch for the three starts, against the entropy of the Gaussian fit (dashed), the best any rotation and per-coordinate affine map can do. Warming up the rotation alone barely helps while the scales start far off; warming up the whole layer starts at the solution. The held-out rows are a different sample from the data the bound is computed on, so the curves can settle slightly below it.
Warming up only the rotation changes little. Its first held-out loss (5.59) is close to the cold start’s (5.74), because the scales start at 1 while the smallest principal variance is 0.11, and both runs take about 15 epochs to reach the dashed line and stop after about 40. Warming up the whole layer starts at the solution, so early stopping ends its run after 7 epochs. All three end within 0.002 nats of the bound (5) on the full data. A warm start pays off when it sets every parameter the data determine, which is the recipe RBIG uses to initialise parametric flows in Part 3.
Recap¶
| Idea | Equation | In code |
|---|---|---|
| the PCA frame decorrelates | (3), (1) | FixedRotation.from_data |
| it stays frozen in training | paramax.NonTrainable, fit_gaussianization_flow | |
| a free matrix booked as a rotation | (2), (3) | collapses; never do this |
| a frame as Householder reflections | (4) | eqx.tree_at on HouseholderRotation.params |
| the PCA frame maximises the likelihood | (5) | warm-start the rotation and the scales |
Next. Rotations are the dense orthogonal mixers. Image and high-dimensional flows also need cheap structured linear layers whose log-determinant is not zero but still easy to compute. The next notebook covers the invertible convolution, parametrised by an LU factorisation, and ActNorm, the data-initialised affine layer.