The coupling pattern
Split, condition, transform: why a coupling layer has a triangular Jacobian, a cheap log-determinant and an inverse that never inverts its network
00 · The coupling pattern¶
The flows of Part 4 Gaussianize each coordinate with a map of its own: within a layer, the map of one coordinate never looks at the others, and only the rotations between layers mix them. A coupling layer Dinh et al., 2017 lets the map of one coordinate depend on the others. It splits the coordinates into two halves, copies the first, and transforms the second with a one-dimensional map whose parameters a neural network computes from the copied half. This one move gives the layer three properties: its Jacobian is triangular, so its log-determinant is a sum; its inverse never inverts the network; and the network can be as large as we like without changing either.
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
from jaxtyping import ArrayLike, Float, Key
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import use_compact_figures
from gauss_flows_maps.bijections import AffineCoupling, MixtureGaussianCDFCoupling
jax.config.update("jax_enable_x64", True)
np.set_printoptions(precision=3, suppress=True)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "equinox", "flowjax", "gauss_flows_maps")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
equinox : 0.13.8
flowjax : 19.1.0
gauss_flows_maps: 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 coupling layer at a glance¶
A coupling layer acts on a point . A mask splits its coordinates into a passive half and an active half , with . A conditioner , a neural network with weights , reads the passive half and returns the parameters of a transformer , a monotone one-dimensional map applied to each active coordinate:
The passive half is copied to the output and also feeds the conditioner; the active half is the only part that changes, and how it changes depends on the passive half.
1. A fresh layer is the identity¶
AffineCoupling uses an affine transformer: the active half is scaled by and shifted by , both computed by an MLP from the passive half,
For the first two coordinates are passive and the last two active. We build one layer and apply it to one point.
# Shapes: state (D_x) = 4; passive (D_A) = 2; active (D_B) = 2
# today (gauss_flows)
# z_A = x_A, z_B = σ_B(x_A) ⊙ x_B + μ_B(x_A), with a 2-layer MLP of width 32 as c_φ
fresh_layer: AffineCoupling = AffineCoupling(
jr.key(0), shape=(4,), nn_width=32, nn_depth=2
)
# x ~ N(0, I), (state)
point: Float[ArrayLike, " state"] = jr.normal(jr.key(1), (4,))
# today (gauss_flows)
# J = ∂z/∂x of the fresh layer, (latent, state)
fresh_jacobian: Float[ArrayLike, "latent state"] = jax.jacfwd(fresh_layer.transform)(
point
)
print(f"x = {np.asarray(point)}")
print(f"z = {np.asarray(fresh_layer.transform(point))}")
print(f"J =\n{np.asarray(fresh_jacobian)}")x = [-1.184 -0.116 0.173 0.957]
z = [-1.184 -0.116 0.173 0.957]
J =
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
The fresh layer returns its input unchanged and its Jacobian is the identity. That is deliberate: gauss_flows starts its couplings as the identity (all but DeepSigmoidCoupling, see notebook 01) by giving the conditioner’s last layer zero weights (zero_readout), so a deep stack of fresh couplings is the identity too, and training moves it from there. The weights of the last layer still receive a gradient at the first step, so the layer can move away from the identity. A transformer with interchangeable components (the mixture CDF and the deep sigmoid) is the exception: its components all start alike, receive the same gradient and stay alike until that is fixed, so a mixture CDF trains as one Gaussian, which is an affine map, and a deep sigmoid as a line plus one sigmoid (gauss_flows#265), and the later notebooks move its weights a little before training.
To see what a coupling does once its conditioner has learned something, we move every weight of the layer by a random amount, a stand-in for a trained layer. Everything below holds for any weights.
# Shapes: leaf = the weight arrays of the layer
# user
# φ ← φ + 0.3 ε with ε ~ N(0, I), for every weight of the layer
def perturb_weights(
layer: eqx.Module, key: jax.Array, scale: float = 0.3
) -> eqx.Module:
"""The layer with every floating-point weight moved by scale times a normal draw."""
# today (equinox)
# the weight arrays φ, with every other field of the layer set to None
weights: eqx.Module = eqx.filter(layer, eqx.is_inexact_array)
# today (jax)
# the weight arrays as a flat list, and how to rebuild the tree
leaves: list[jax.Array]
treedef: jax.tree_util.PyTreeDef
leaves, treedef = jax.tree.flatten(weights)
# one key per weight array, (leaf)
keys: Key[jax.Array, " leaf"] = jr.split(key, len(leaves))
# φ + scale ε, one array per leaf
moved: list[jax.Array] = [
leaf + scale * jr.normal(leaf_key, leaf.shape, leaf.dtype)
for leaf, leaf_key in zip(leaves, keys, strict=True)
]
return eqx.combine(jax.tree.unflatten(treedef, moved), layer)We apply it to the fresh layer.
# user
# a coupling layer with random conditioner weights
layer: AffineCoupling = perturb_weights(fresh_layer, jr.key(7))Scalar = Float[ArrayLike, ""]
output: Float[ArrayLike, " latent"]
log_det: Scalar
# today (gauss_flows)
# z = f(x) and log |det J_f(x)|, (latent), ()
output, log_det = layer.transform_and_log_det(point)
print(f"x = {np.asarray(point)}")
print(f"z = {np.asarray(output)}")
print(
f"coordinates left unchanged: {np.flatnonzero(np.asarray(output) == np.asarray(point)).tolist()}"
)x = [-1.184 -0.116 0.173 0.957]
z = [-1.184 -0.116 0.114 1.084]
coordinates left unchanged: [0, 1]
The first two coordinates pass through exactly; the last two are scaled and shifted by amounts the conditioner computed from the first two. That conditioning is how a coupling models dependence between coordinates, which no per-coordinate map of Part 4 can do within one layer.
2. The triangular Jacobian¶
The Jacobian (2) of a coupling has a fixed pattern. The passive outputs do not depend on , and each active output depends on its own active input only through the elementwise transformer, so the Jacobian is block lower-triangular:
The determinant of a triangular matrix is the product of its diagonal, so the log-determinant is a sum over the active half, and the conditioner never has to be differentiated for it:
We check both against the Jacobian that autodiff builds.
LatentState = Float[ArrayLike, "latent state"]
# today (jax)
# J = ∂z/∂x with random conditioner weights, (latent, state)
jacobian: LatentState = jax.jacfwd(layer.transform)(point)
print(f"J =\n{np.asarray(jacobian)}")
print(
f"largest entry above the diagonal: {float(jnp.abs(jnp.triu(jacobian, 1)).max()):.1e}"
)
# log |det J|, from a dense LU of the autodiff Jacobian
dense_log_det: Scalar = jnp.linalg.slogdet(jacobian)[1]
# ∑_d log |J_dd|, the diagonal alone
diagonal_log_det: Scalar = jnp.sum(jnp.log(jnp.abs(jnp.diag(jacobian))))
print(f"log |det J|, dense: {float(dense_log_det):+.6f}")
print(f"∑ log |J_dd|, diagonal: {float(diagonal_log_det):+.6f}")
print(f"the layer's log_det: {float(log_det):+.6f}")J =
[[ 1. 0. 0. 0. ]
[ 0. 1. 0. 0. ]
[ 0.343 -0.583 0.312 0. ]
[-0.189 0.758 0. 0.354]]
largest entry above the diagonal: 0.0e+00
log |det J|, dense: -2.201140
∑ log |J_dd|, diagonal: -2.201140
the layer's log_det: -2.201140
fig, ax = plt.subplots(figsize=(5, 4.4))
image = ax.imshow(np.abs(np.asarray(jacobian)), cmap="viridis")
ax.set(
xticks=range(4),
yticks=range(4),
xlabel="input coordinate j",
ylabel="output coordinate i",
)
ax.set_title("|J_ij| of a coupling layer")
fig.colorbar(image, ax=ax, fraction=0.046)
fig.tight_layout()
plt.show()
Figure 1:The magnitude of each entry of the coupling’s Jacobian. The upper-right block is zero, the passive diagonal is one and the active diagonal holds the scales σ_B; the lower-left block, which the conditioner fills, does not enter the determinant.
The block above the diagonal is exactly zero, and the three log-determinants agree to machine precision. This is why coupling flows scale: the log-determinant of a general Jacobian costs , and that of a coupling costs . The conditioner fills only the block below the diagonal, which the determinant ignores, so it can be as large as we like at no cost to the log-determinant.
3. The inverse never inverts the network¶
Inverting the layer is just as cheap. Given , the passive half comes back for free, and since it is the conditioner’s input we can recompute the same parameters with a forward pass and invert only the one-dimensional transformer:
The conditioner, which may be a large network, is only ever run forwards. We round-trip 2,000 points through the layer, with the test of (4).
# Shapes: sample (N) = 2,000
SampleState = Float[ArrayLike, "sample state"]
# x ~ N(0, I), (sample, state)
samples: SampleState = jr.normal(jr.key(2), (2000, 4))
# today (gauss_flows)
# z = f(x), (sample, latent)
latents: Float[ArrayLike, "sample latent"] = jax.vmap(layer.transform)(samples)
# today (gauss_flows)
# x̂ = f⁻¹(z), (sample, state)
recovered: SampleState = jax.vmap(layer.inverse)(latents)
print(f"round trip, max |x̂ - x| = {float(jnp.abs(recovered - samples).max()):.1e}")round trip, max |x̂ - x| = 8.9e-16
The inverse also returns its own log-determinant, which should be the negative of the forward one at matching points.
inverse_log_det: Scalar
# today (gauss_flows)
# x = f⁻¹(z) and log |det J_{f⁻¹}(z)|, (state), ()
_, inverse_log_det = layer.inverse_and_log_det(output)
print(f"forward log_det = {float(log_det):+.6f}")
print(f"inverse log_det = {float(inverse_log_det):+.6f}")
print(f"sum = {float(log_det + inverse_log_det):.1e}")forward log_det = -2.201140
inverse log_det = +2.201140
sum = 0.0e+00
The round trip is exact to machine precision and the two log-determinants cancel. Both directions run the conditioner forwards, so sampling and density evaluation cost the same, unlike an autoregressive flow, where one of the two directions has to be computed one coordinate at a time.
4. Swapping the transformer¶
Nothing above used the affine form of , only that it acts on each active coordinate on its own and is invertible. MixtureGaussianCDFCoupling uses the Gaussianizing map of a Gaussian mixture from Part 1 as , with the mixture’s weights, means and scales computed by the conditioner. We check the same three properties on a layer with random weights.
# today (gauss_flows)
# z_B = Φ⁻¹(F_θ(x_B)) with an 8-component mixture CDF F_θ, θ = c_φ(x_A)
mixture_layer: MixtureGaussianCDFCoupling = perturb_weights(
MixtureGaussianCDFCoupling(
jr.key(0), shape=(4,), n_components=8, nn_width=32, nn_depth=2
),
jr.key(8),
)
mixture_output: Float[ArrayLike, " latent"]
mixture_log_det: Scalar
# today (gauss_flows)
# z = f(x) and log |det J_f(x)|, (latent), ()
mixture_output, mixture_log_det = mixture_layer.transform_and_log_det(point)
# today (jax)
# J = ∂z/∂x, (latent, state)
mixture_jacobian: LatentState = jax.jacfwd(mixture_layer.transform)(point)
print(
f"largest entry above the diagonal: {float(jnp.abs(jnp.triu(mixture_jacobian, 1)).max()):.1e}"
)
print(f"log |det J|, dense: {float(jnp.linalg.slogdet(mixture_jacobian)[1]):+.6f}")
print(f"the layer's log_det: {float(mixture_log_det):+.6f}")largest entry above the diagonal: 0.0e+00
log |det J|, dense: -6.221491
the layer's log_det: -6.221491
# today (gauss_flows)
# x̂ = f⁻¹(f(x)), with T_θ⁻¹ found by bisection, (sample, state)
mixture_recovered: SampleState = jax.vmap(mixture_layer.inverse)(
jax.vmap(mixture_layer.transform)(samples)
)
print(
f"round trip, max |x̂ - x| = {float(jnp.abs(mixture_recovered - samples).max()):.1e}"
)round trip, max |x̂ - x| = 1.2e-06
The Jacobian is triangular and the log-determinants agree, as for the affine layer. The round trip is no longer exact: a mixture CDF has no closed-form inverse, so the layer inverts by bisection, and the error is the bisection’s tolerance of 10-6, not machine precision. The inverse still never touches the network; only the one-dimensional root find is new. The transformer and the conditioner are independent choices, which is why the next two notebooks can take them one at a time.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| split, condition, transform | (1) | AffineCoupling, MixtureGaussianCDFCoupling |
| the affine transformer | (2) | AffineCoupling |
| a fresh layer is the identity (all but the deep sigmoid) | zero_readout on the conditioner’s last layer | |
| a triangular Jacobian | (3) | jax.jacfwd(layer.transform) |
| a log-determinant that is a sum | (4) | layer.transform_and_log_det |
| an inverse that runs the network forwards | (5) | layer.inverse, bisection for a mixture CDF |
One coupling layer transforms only its active half, so a flow alternates the mask from layer to layer, and every coordinate is transformed in some layers and conditions the others in the rest (notebook 03, mask design).
Next. Any monotone one-dimensional map can be the transformer. Notebook 01 goes through the ones gauss_flows offers (affine, mixture CDF, deep sigmoid, rational-quadratic spline) and what each can express.
- Dinh, L., Sohl-Dickstein, J., & Bengio, S. (2017). Density Estimation using Real NVP. International Conference on Learning Representations (ICLR).