Depth, gradients and residual maps
How much stacking coupling layers buys on a spiral, how the gradient grows with depth at the identity start, and the residual maps that trade the triangular Jacobian for a fixed-point inverse
07 · Depth, gradients and residual maps¶
A coupling layer transforms only its active half, so a coupling flow is a stack (1) of layers with alternating masks, and its power comes from depth. This notebook looks at that axis: what depth buys on a curved target, how the gradient that training sees grows as the stack deepens, and the residual maps that give up the coupling’s triangular Jacobian for more freedom in each layer.
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.*")
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
import optax
import optimistix as optx
from flowjax.bijections import Chain, Flip, Invert
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Float
from pipekit_train import ArrayDataset, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import SCATTER_KW, style_ax, use_compact_figures
from gauss_flows_maps.bijections import AffineCoupling
from gauss_flows_models.flows import coupling_gaussianization_flow
from gauss_flows_models.inference import negative_log_likelihood
rng = np.random.default_rng(0)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark(
"jax",
"numpy",
"optax",
"optimistix",
"flowjax",
"pipekit_train",
"gauss_flows_models",
)Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
optax : 0.2.8
optimistix : 0.1.0
flowjax : 19.1.0
pipekit_train : 0.3.4
gauss_flows_models: 0.3.1
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
The target is a two-armed spiral: a radius drawn uniformly from 0.5 to 3.5, the point or its mirror image through the origin, and noise of standard deviation 0.08, standardised per coordinate. We draw points and split them into training rows and held-out rows; the notebook runs in float32.
# Shapes: sample (N) = 4,000; state (D_x) = 2; train (N_t) = 3,000; held_out (N_v) = 1,000
PerSample = Float[ArrayLike, " sample"]
SampleState = Float[ArrayLike, "sample state"]
# t ~ 𝒰(0.5, 3.5), the radius along an arm, (sample)
radius: PerSample = rng.uniform(0.5, 3.5, 4000)
# ±1, which of the two arms, (sample)
arm: PerSample = rng.integers(0, 2, 4000) * 2 - 1
# ±(t cos 2.5t, t sin 2.5t) + ε with ε ~ 𝒩(0, 0.08² I), (sample, state)
spiral: SampleState = arm[:, None] * np.stack(
[radius * np.cos(2.5 * radius), radius * np.sin(2.5 * radius)], axis=1
) + 0.08 * rng.standard_normal((4000, 2))# x = (spiral − x̄) / s, in float32, (sample, state)
samples: SampleState = ((spiral - spiral.mean(axis=0)) / spiral.std(axis=0)).astype(
np.float32
)
# the training rows, (train, state)
train_points: Float[ArrayLike, "train state"] = samples[:3000]
# the held-out rows, (held_out, state)
held_points: Float[ArrayLike, "held_out state"] = samples[3000:]1. What depth buys¶
coupling_gaussianization_flow stacks rational-quadratic spline couplings with a flip after each, so consecutive layers have opposite active halves. Each coupling has 8 spline bins on and a conditioner MLP of width 32 and depth 2. The factory builds a trainable base (gauss_flows#256) and has no base_dist argument, so we swap the base for a fixed with eqx.tree_at.
# today (gauss_flows)
# K spline couplings with a flip after each, and a fixed 𝒩(0, I) base
def spline_flow(depth: int) -> Transformed:
"""A spline coupling flow of ``depth`` layers."""
# today (gauss_flows)
# K spline couplings with a trainable base
flow: Transformed = coupling_gaussianization_flow(
jr.key(0),
n_dims=2,
n_layers=depth,
n_bins=8,
nn_width=32,
nn_depth=2,
interval=4.0,
)
# today (equinox)
# the base swapped for a fixed 𝒩(0, I)
return eqx.tree_at(lambda old: old.base_dist, flow, StandardNormal((2,)))The training loop is that of Part 4, at one peak learning rate of 10-2: pipekit-train on the mean negative log-likelihood (1), Adam with gradients clipped to a global norm of 1 on a one-cycle cosine rate, 3,000 steps of 512 rows, and the held-out loss at the end.
# Shapes: batch (N_b) = 512
Scalar = Float[ArrayLike, ""]
# user
# pipekit-train's task: 𝓛(θ) on one batch
class FlowNLL:
"""pipekit-train's task: the mean negative log-likelihood of a batch."""
# user
# 𝓛(θ) = −(1/N_b) ∑ₙ log p_x(xₙ; θ), also logged
def loss_fn(self, flow, batch, key):
# the points of the batch; its targets are empty, (batch, state)
batch_points: Float[ArrayLike, "batch state"]
batch_points, _ = batch
# today (gauss_flows)
# −(1/N_b) ∑ₙ log p_x(xₙ; θ)
loss: Scalar = negative_log_likelihood(flow, batch_points)
return loss, {"loss": loss}# today (optax)
# the learning rate of each step: up to 10⁻², then down to almost zero
schedule: optax.Schedule = optax.cosine_onecycle_schedule(
transition_steps=3000, peak_value=1e-2
)
# user
# the settings every run shares
loop_settings: dict = {
"optimizer_config": {"name": "adam", "lr": schedule, "clip_norm": 1.0},
"val_dataset": ArrayDataset(held_points, ()),
"task": FlowNLL(),
"max_steps": 3000,
"steps_per_epoch": 100,
"eval_every_n_steps": 3000,
"log_every_n_steps": 100,
"batch_size": 512,
"seed": 1,
}# user
# θ after 3,000 steps from `flow`
def train_flow(flow: Transformed) -> Transformed:
"""Train ``flow`` with the shared settings."""
# today (pipekit)
# the flow as a trainable model
model_op = EquinoxModelOp(flow)
# today (pipekit)
# θ after 3,000 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = TrainingLoop(
model_op,
ArrayDataset(train_points, ()),
callbacks=(History(),),
**loop_settings,
).run()
return trained_op.moduleWe train flows of 2, 4, 8 and 16 layers; the four runs take a few minutes.
# the depths K, in coupling layers
depths: list = [2, 4, 8, 16]
# user
# each depth's flow after 3,000 steps
trained: dict = {depth: train_flow(spline_flow(depth)) for depth in depths}
for depth, flow in trained.items():
# today (gauss_flows)
# −(1/N_t) ∑ₙ log p_x(xₙ) on the training rows
train_nll: float = float(negative_log_likelihood(flow, train_points))
# today (gauss_flows)
# −(1/N_v) ∑ₙ log p_x(xₙ) on the held-out rows
held_nll: float = float(negative_log_likelihood(flow, held_points))
print(
f"K = {depth:2d}: NLL {train_nll:.3f} on training rows, {held_nll:.3f} held out"
)K = 2: NLL 1.420 on training rows, 1.505 held out
K = 4: NLL 1.338 on training rows, 1.463 held out
K = 8: NLL 1.308 on training rows, 1.486 held out
K = 16: NLL 1.286 on training rows, 1.507 held out
# Shapes: line = 150 points along each axis; test = 150 × 150 grid points
# 150 points from −2.5 to 2.5, (line)
grid_axis: Float[ArrayLike, " line"] = np.linspace(-2.5, 2.5, 150)
# the 150 × 150 grid over [−2.5, 2.5]², as rows, (test, state)
grid_points: Float[ArrayLike, "test state"] = (
np.stack(np.meshgrid(grid_axis, grid_axis), axis=-1)
.reshape(-1, 2)
.astype(np.float32)
)fig, axes = plt.subplots(1, 5, figsize=(18, 3.9), sharey=True)
axes[0].scatter(train_points[:, 0], train_points[:, 1], **SCATTER_KW)
axes[0].set_title("training rows")
for ax, (depth, flow) in zip(axes[1:], trained.items(), strict=True):
# today (flowjax)
# p_x on the grid, (test)
density: Float[ArrayLike, " test"] = np.exp(
np.asarray(jax.vmap(flow.log_prob)(grid_points))
)
ax.contourf(
grid_axis, grid_axis, density.reshape(150, 150), levels=20, cmap="viridis"
)
ax.set_title(f"K = {depth}")
for ax in axes:
ax.set_aspect("equal")
ax.set(xlim=(-2.5, 2.5), ylim=(-2.5, 2.5))
fig.tight_layout()
plt.show()
Figure 1:The training rows of the spiral (left) and the density of the trained spline coupling flows with 2, 4, 8 and 16 layers.
Depth helps up to a point. The training NLL falls with every doubling, from 1.420 at to 1.286 at , but the held-out NLL is lowest at (1.463) and climbs back to 1.486 at and 1.507 at , worse than two layers (1.505); the gap between training and held-out rows widens from 0.085 to 0.221. Two layers already trace both arms in the figure, and the deeper flows draw them with more ragged edges, which fits the overfitting the numbers show. On 3,000 points of a two-dimensional spiral, four spline layers of width 32 are enough, and more depth needs more data or regularisation to pay.
2. The gradient at the start of training¶
Gradients flow back through every layer, so a deeper stack can see a larger gradient. We measure the global norm of the loss’s gradient over all the parameters at the start of training, on 1,000 training rows, for spline stacks and for stacks of AffineCoupling layers with a flip after each, at depths of 2 to 16.
# user
# K affine couplings with a flip after each, and a fixed 𝒩(0, I) base
def affine_flow(depth: int) -> Transformed:
"""An affine coupling flow of ``depth`` layers."""
# the couplings and flips, in the density direction
blocks: list = []
for key in jr.split(jr.key(0), depth):
# today (gauss_flows)
# one affine coupling with a conditioner MLP of width 32 and depth 2, then a flip
blocks += [
AffineCoupling(key, shape=(2,), nn_width=32, nn_depth=2),
Flip(shape=(2,)),
]
return Transformed(StandardNormal((2,)), Invert(Chain(blocks)))
# user
# ‖∇_θ 𝓛‖₂ over all parameters, on the first 1,000 training rows
def gradient_norm(flow: Transformed) -> float:
"""The global norm of the loss's gradient at ``flow``."""
# today (equinox)
# ∇_θ 𝓛, a tree shaped like the flow
gradient: Transformed = eqx.filter_grad(negative_log_likelihood)(
flow, train_points[:1000]
)
return float(optax.global_norm(eqx.filter(gradient, eqx.is_inexact_array)))# the depths K of the gradient study
gradient_depths: list = [2, 4, 8, 16]
# user
# ‖∇_θ 𝓛‖₂ at the start, for each kind of stack and depth
norms: dict = {
"spline": [gradient_norm(spline_flow(depth)) for depth in gradient_depths],
"affine": [gradient_norm(affine_flow(depth)) for depth in gradient_depths],
}
for name, values in norms.items():
print(
f"{name}: gradient norm {np.round(values, 3)}, divided by √K {np.round(np.array(values) / np.sqrt(gradient_depths), 3)}"
)spline: gradient norm [0.459 0.631 0.886 1.265], divided by √K [0.325 0.315 0.313 0.316]
affine: gradient norm [0.081 0.102 0.139 0.196], divided by √K [0.057 0.051 0.049 0.049]
fig, ax = plt.subplots(figsize=(7.5, 4.4))
for name, colour in [("spline", "C2"), ("affine", "C3")]:
ax.plot(gradient_depths, norms[name], "o-", color=colour, lw=2, label=name)
ax.plot(
gradient_depths,
norms[name][0] * np.sqrt(np.array(gradient_depths) / 2),
"--",
color=colour,
lw=1,
label=f"{name}, ∝ √K",
)
ax.set(
xscale="log",
yscale="log",
xlabel="coupling layers K",
ylabel="gradient norm at the start",
xticks=gradient_depths,
xticklabels=[str(depth) for depth in gradient_depths],
)
ax.legend()
style_ax(ax)
plt.show()
Figure 2:The global norm of the loss’s gradient at the start of training against the number of coupling layers, for spline (green) and affine (red) stacks, on log–log axes. The dashed lines grow like √K from each stack’s value at K = 2.
The gradient grows like : divided by , the spline norms are 0.325, 0.315, 0.313 and 0.316, and the affine norms 0.057, 0.051, 0.049 and 0.049. The spline and affine couplings of gauss_flows start as the identity, so every layer sees the data up to flips and contributes a gradient of about the same size, and such contributions add to a norm of about times one of them. Deep coupling stacks are sometimes said to see gradients ten times larger and to need normalisation layers between couplings; that does not happen at the identity start, and we have not measured random starts. The growth still meets the training loop: clipping to a global norm of 1 leaves the shallow spline stacks alone but rescales the 16-layer one, whose norm is 1.265, from its first step. The affine stacks start with gradients about six times smaller than the spline stacks at every depth.
3. Residual maps¶
A coupling gets its cheap log-determinant from its triangular Jacobian, at the price of transforming only half the coordinates in each layer. A residual map transforms them all,
where the residual branch is any network, with no split and no mask. It is invertible when is a contraction, : then in one dimension, so the map is increasing. Its inverse has no closed form, but the contraction makes the fixed-point iteration
converge to the with from any start. We try it on , whose Lipschitz constant is , once with and once with , with optimistix’s fixed-point solver.
# Shapes: test = 400 points on [−3, 3]
PerTestPoint = Float[ArrayLike, " test"]
# x on [−3, 3], (test)
test_points: PerTestPoint = jnp.linspace(-3.0, 3.0, 400)
# today (optimistix)
# xⁿ⁺¹ = y − r(xⁿ), stopped at a tolerance of 10⁻⁶
solver = optx.FixedPointIteration(rtol=1e-6, atol=1e-6)
# user
# x with x + a sin(ωx) = y, by fixed-point iteration from x⁰ = y
def residual_inverse(
output: Scalar, amplitude: float, frequency: float
) -> optx.Solution:
"""The fixed-point solve that inverts y = x + amplitude · sin(frequency · x)."""
# today (optimistix)
# the fixed point of x ↦ y − a sin(ωx)
return optx.fixed_point(
lambda guess, target: target - amplitude * jnp.sin(frequency * guess),
solver,
output,
args=output,
max_steps=200,
throw=False,
)# the two residual branches, (a, ω)
branches: list = [(0.3, 1.0), (0.9, 1.5)]
for amplitude, frequency in branches:
# y = x + a sin(ωx), (test)
outputs: PerTestPoint = test_points + amplitude * jnp.sin(frequency * test_points)
# user
# the fixed-point solve at every y
solution: optx.Solution = jax.vmap(
lambda value, a=amplitude, w=frequency: residual_inverse(value, a, w)
)(outputs)
print(
f"a = {amplitude}, ω = {frequency}: Lip(r) = {amplitude * frequency:.2f}, increasing {bool(jnp.all(jnp.diff(outputs) > 0))}, "
f"converged {bool(jnp.all(solution.result == optx.RESULTS.successful))}, max |x̂ - x| = {float(jnp.abs(solution.value - test_points).max()):.1e}, "
f"most iterations {int(solution.stats['num_steps'].max())}"
)a = 0.3, ω = 1.0: Lip(r) = 0.30, increasing True, converged True, max |x̂ - x| = 1.2e-06, most iterations 11
a = 0.9, ω = 1.5: Lip(r) = 1.35, increasing False, converged False, max |x̂ - x| = 1.7e+00, most iterations 200
fig, axes = plt.subplots(1, 2, figsize=(12, 4.4), sharey=True)
for ax, (amplitude, frequency), colour in zip(
axes, branches, ["C2", "C3"], strict=True
):
ax.plot(
test_points,
test_points + amplitude * jnp.sin(frequency * test_points),
color=colour,
lw=2,
label=f"y = x + {amplitude} sin({frequency}x)",
)
ax.plot([-3, 3], [-3, 3], "k--", lw=1, label="identity")
ax.set(title=f"Lip(r) = {amplitude * frequency:.2f}", xlabel="x")
ax.legend()
style_ax(ax)
axes[0].set_ylabel("y")
fig.tight_layout()
plt.show()
Figure 3:The residual map y = x + a sin(ωx) for a contraction, Lip(r) = 0.3 (left), and for Lip(r) = 1.35 (right), with the identity dashed. The first is increasing and so invertible; the second folds back on itself, so some y have three preimages.
The contraction inverts: with the map is increasing, the fixed-point iteration (2) converges at all 400 points in at most 11 steps, and the round trip is exact to , the solver’s tolerance in float32. With the map folds back on itself (right panel), so it has no inverse, and the iteration fails at some points after 200 steps with errors up to 1.7. A residual layer pays for its freedom twice over: the inverse is an iteration rather than a formula, and the log-determinant is cheap only in one dimension, while in dimensions it is the log-determinant of a full matrix. Invertible residual networks (i-ResNets) Behrmann et al., 2019 keep by normalising the spectral norm of every weight matrix and estimate that log-determinant with a power series; a coupling layer avoids both costs by construction, which is why gauss_flows builds its flows from couplings.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| a coupling flow is a stack of layers | (1), (1) | coupling_gaussianization_flow(key, n_dims=2, n_layers=K) |
| what depth buys | (1) | held-out NLL of 2 to 16 layers, pipekit-train |
| the gradient at the start | eqx.filter_grad(negative_log_likelihood), optax.global_norm | |
| a residual map and its inverse | (1), (2) | optx.fixed_point with optx.FixedPointIteration |
This closes Part 5: the coupling pattern (00), the transformers (01), the conditioners (02), the masks (03), the comparison with diagonal flows (04), the warm start (05), the equivalence with a diagonal flow (06) and depth (07).
Next. Part 6 takes depth to its limit: instead of stacking layers, a continuous-time flow transports the data to along an ordinary differential equation.
- Behrmann, J., Grathwohl, W., Chen, R. T. Q., Duvenaud, D., & Jacobsen, J.-H. (2019). Invertible Residual Networks. International Conference on Machine Learning (ICML).