Layer-wise inspection
Following the data through a flow one block at a time, on training and held-out rows, for a greedy fit and a trained flow
02 · Layer-wise inspection¶
The notebooks so far judged a flow by one number, its likelihood. A Gaussianization flow is a composition (1) of rotations and marginal maps, so we can also apply the blocks one at a time, keep each intermediate state (2), and run the diagnostics of Part 0 on it. The last section of the Gaussianization flow example shows the states of a trained flow as scatter plots; this notebook measures them, on training and on held-out rows, for a greedy fit and for a trained flow.
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
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Bool, Float
from pipekit_train import ArrayDataset, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from scipy import stats
from sklearn.datasets import make_moons
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import SCATTER_KW, style_ax, use_compact_figures
from gauss_flows_models.flows import gaussianization_flow
from gauss_flows_models.inference import fit_rbig, 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", "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
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 data and the precision are those of notebooks 00 and 01: two moons, standardised, split into training rows and held-out rows, in float32 because fit_rbig cannot run in float64 today (gauss_flows#247).
# Shapes: sample (N) = 4,000; state (D_x) = 2; train (N_t) = 3,000; held_out (N_v) = 1,000
SampleState = Float[ArrayLike, "sample state"]
# today (scikit-learn)
# two interleaved half circles with noise of standard deviation 0.08, (sample, state)
raw: SampleState
raw, _ = make_moons(n_samples=4000, noise=0.08, random_state=0)
# x = (raw − x̄) / s, in float32, (sample, state)
samples: SampleState = ((raw - raw.mean(axis=0)) / raw.std(axis=0)).astype(np.float32)
# a random order of the rows, (sample)
order: Float[ArrayLike, " sample"] = rng.permutation(4000)
# the training rows, (train, state)
train_points: Float[ArrayLike, "train state"] = samples[order[:3000]]
# the held-out rows, (held_out, state)
held_points: Float[ArrayLike, "held_out state"] = samples[order[3000:]]1. Taking a flow apart¶
We fit RBIG greedily with fit_rbig, layers of a PCA rotation and an 8-component mixture marginal, as in notebook 01. Its bijection is Invert(Chain([...])), and the density direction runs the Chain forwards, so its 16 blocks, in order, are the maps of (1).
# today (gauss_flows)
# 8 greedy layers of a PCA rotation and an 8-component mixture fitted by EM
greedy_flow: Transformed = fit_rbig(
jnp.asarray(train_points), n_layers=8, n_components=8, random_state=0
)
# the 16 blocks f_k in the density direction
greedy_blocks: list = list(greedy_flow.bijection.bijection.bijections)
print(
f"{len(greedy_blocks)} blocks: {[type(block).__name__ for block in greedy_blocks[:4]]} ..."
)16 blocks: ['FixedRotation', 'MixtureGaussianCDF', 'FixedRotation', 'MixtureGaussianCDF'] ...
One function runs a list of blocks on a set of points and keeps every intermediate state and every block’s log-determinant.
# Shapes: block = 16 blocks f_k
# user
# xₖ = f_k(xₖ₋₁) and log |det J_{f_k}(xₖ₋₁)| for every block, (block, sample, state), (block, sample)
def run_blocks(
blocks: list, points: Float[ArrayLike, "sample state"]
) -> tuple[Float[ArrayLike, "block sample state"], Float[ArrayLike, "block sample"]]:
"""The states after each block, and each block's log-determinant."""
# the states, one entry per block
states: list = []
# the log-determinants, one entry per block
logdets: list = []
# x₀ = x, (sample, state)
state: Float[ArrayLike, "sample state"] = points
for block in blocks:
logdet: Float[ArrayLike, " sample"]
# today (flowjax)
# xₖ = f_k(xₖ₋₁) and log |det J_{f_k}(xₖ₋₁)|, (sample, state), (sample)
state, logdet = jax.vmap(block.transform_and_log_det)(state)
states.append(np.asarray(state))
logdets.append(np.asarray(logdet))
return np.stack(states), np.stack(logdets)The blocks should reproduce the flow: the last state is , and the log-density of a deep flow (5) is the base log-density of the last state plus the sum of the blocks’ log-determinants. We check both on the training rows.
# Shapes: block = 16; train (N_t) = 3,000
# user
# the greedy fit's states and log-determinants on the training rows, (block, train, state), (block, train)
greedy_train_states: Float[ArrayLike, "block train state"]
greedy_train_logdets: Float[ArrayLike, "block train"]
greedy_train_states, greedy_train_logdets = run_blocks(greedy_blocks, train_points)
# today (flowjax)
# z = f(x) from the whole flow, (train, latent)
whole_latent: Float[ArrayLike, "train latent"] = np.asarray(
jax.vmap(greedy_flow.bijection.inverse)(train_points)
)
# today (scipy)
# log p_z(x_K) + ∑ₖ log |det J_{f_k}(xₖ₋₁)|, (train)
block_logp: Float[ArrayLike, " train"] = stats.norm.logpdf(greedy_train_states[-1]).sum(
axis=1
) + greedy_train_logdets.sum(axis=0)print(
f"largest |x_K - f(x)| : {np.abs(greedy_train_states[-1] - whole_latent).max():.1e}"
)
print(
f"largest |block sum - log_prob| : {np.abs(block_logp - np.asarray(jax.vmap(greedy_flow.log_prob)(train_points))).max():.1e}"
)largest |x_K - f(x)| : 0.0e+00
largest |block sum - log_prob| : 7.6e-07
Both agree to float32 rounding, so anything we measure on the intermediate states is a measurement of the flow itself.
2. The greedy fit on its training rows¶
We look first at the states after whole layers, a rotation and a marginal map each.
fig, axes = plt.subplots(1, 5, figsize=(17, 3.8), sharex=True, sharey=True)
axes[0].scatter(train_points[:, 0], train_points[:, 1], color="C0", **SCATTER_KW)
axes[0].set(title="input", ylabel="second coordinate")
for ax, layer in zip(axes[1:], [1, 2, 4, 8]):
ax.scatter(
greedy_train_states[2 * layer - 1][:, 0],
greedy_train_states[2 * layer - 1][:, 1],
color="C1",
**SCATTER_KW,
)
ax.set(title=f"after layer {layer}")
for ax in axes:
ax.set(xlim=(-4, 4), ylim=(-4, 4), xlabel="first coordinate")
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:The training rows before the greedy fit and after its layers 1, 2, 4 and 8, each layer a PCA rotation followed by a mixture marginal map.
The first layer unrolls the moons into an S-shaped band, and the later layers fold it into parallel stripes that are still there after layer 8. To measure what each block does we compute four numbers after every block: the correlation of the two coordinates, the mean absolute excess kurtosis of the coordinates (2), the joint test over 64 projections (3), and the block’s mean log-determinant.
# Shapes: direction (J) = 64
# αⱼ, 64 angles evenly spread over [0, π), (direction)
angles: Float[ArrayLike, " direction"] = np.linspace(0, np.pi, 64, endpoint=False)
# unit directions eⱼ = (cos αⱼ, sin αⱼ), (direction, state)
directions: Float[ArrayLike, "direction state"] = np.column_stack(
[np.cos(angles), np.sin(angles)]
)
# user
# KS_max = maxⱼ supₜ |F̂_{N,j}(t) − Φ(t)|
def projection_ks(points: Float[ArrayLike, "sample state"]) -> float:
"""The largest Kolmogorov-Smirnov distance of a projection of ``points`` to N(0, 1)."""
# eⱼᵀ xₙ, (sample, direction)
projections: Float[ArrayLike, "sample direction"] = (
np.asarray(points) @ directions.T
)
return max(stats.kstest(projections[:, j], "norm").statistic for j in range(64))# Shapes: block = 16
# user
# |corr|, mean |γ₂|, KS_max and the mean log-determinant after every block, as rows of a table
def block_diagnostics(
states: Float[ArrayLike, "block sample state"],
logdets: Float[ArrayLike, "block sample"],
) -> dict:
"""Four per-block diagnostics, each an array over the blocks."""
return {
"corr": np.array([abs(np.corrcoef(state.T)[0, 1]) for state in states]),
"kurtosis": np.array(
[np.abs(stats.kurtosis(state, axis=0)).mean() for state in states]
),
"ks": np.array([projection_ks(state) for state in states]),
"logdet": logdets.mean(axis=1),
}# user
# the input's |corr|, mean |γ₂| and KS_max on the training rows
input_train: dict = block_diagnostics(train_points[None], np.zeros((1, 3000)))
# user
# the greedy fit's diagnostics on the training rows
greedy_train: dict = block_diagnostics(greedy_train_states, greedy_train_logdets)
# user
# one row per block: its type and the four diagnostics
def print_table(blocks: list, diagnostics: dict, start: dict) -> None:
"""Print the diagnostics after every block, below those of the input."""
print("block type |corr| mean|kurt| KS_max mean log|det J|")
print(
f"input {start['corr'][0]:6.3f} {start['kurtosis'][0]:9.3f} {start['ks'][0]:6.3f}"
)
for k, block in enumerate(blocks):
print(
f"{k + 1:5d} {type(block).__name__[:9]:9s} {diagnostics['corr'][k]:6.3f} {diagnostics['kurtosis'][k]:9.3f} {diagnostics['ks'][k]:6.3f} {diagnostics['logdet'][k]:+8.3f}"
)
# user
# the table for the training rows
print_table(greedy_blocks, greedy_train, input_train)block type |corr| mean|kurt| KS_max mean log|det J|
input 0.441 1.044 0.149
1 FixedRota 0.000 1.233 0.151 +0.000
2 MixtureGa 0.015 0.059 0.087 +0.527
3 FixedRota 0.000 0.824 0.087 +0.000
4 MixtureGa 0.009 0.172 0.057 +0.193
5 FixedRota 0.000 0.775 0.058 +0.000
6 MixtureGa 0.011 0.052 0.054 +0.088
7 FixedRota 0.000 0.042 0.053 +0.000
8 MixtureGa 0.008 0.201 0.056 +0.013
9 FixedRota 0.000 0.102 0.056 +0.000
10 MixtureGa 0.012 0.277 0.052 +0.020
11 FixedRota 0.000 0.201 0.051 +0.000
12 MixtureGa 0.001 0.199 0.050 +0.004
13 FixedRota 0.000 0.943 0.049 +0.000
14 MixtureGa 0.001 0.206 0.058 +0.052
15 FixedRota 0.000 0.251 0.058 +0.000
16 MixtureGa 0.005 0.120 0.049 +0.021
Each PCA rotation sets the correlation of the training rows to exactly zero, since it is fitted to them, and the marginal maps leave it below 0.02. The kurtosis alternates in the first three layers, as the source of this tutorial describes: each rotation raises it (to 1.23, 0.82 and 0.78) and each marginal map brings it back down (to 0.06, 0.17 and 0.05). After that the pattern breaks: the marginal maps of layers 4 and 5 raise it, and the rotation of layer 7 takes it to 0.94. The log-determinants say where the likelihood comes from: the marginal maps of the first three layers contribute 0.53, 0.19 and 0.09 nats per point, 0.81 of the 0.92 that all eight contribute, and falls from 0.149 to 0.057 by block 4 and then stays between 0.049 and 0.058.
How small can get? We compare it with its value on samples that really are standard normal, for the two sample sizes of this notebook.
# user
# the 95% quantile of KS_max over 50 draws of N points from 𝒩(0, I), for N = 3,000 and 1,000
null_threshold: dict = {
size: np.quantile(
[projection_ks(rng.standard_normal((size, 2))) for _ in range(50)], 0.95
)
for size in [3000, 1000]
}
print(
f"95% quantile of KS_max under N(0, I): {null_threshold[3000]:.3f} for 3,000 points, {null_threshold[1000]:.3f} for 1,000"
)95% quantile of KS_max under N(0, I): 0.030 for 3,000 points, 0.055 for 1,000
The fit ends at 0.049 on its own training rows, above the 0.030 of a standard normal of the same size, so eight layers of PCA rotations do not Gaussianize the moons. That is the stall of PCA on two moons that Part 3 found: the marginal steps leave the coordinates uncorrelated with unit variance, so the covariance that PCA diagonalises is already close to the identity and its frame is set by small differences. The stripes in the figure are what is left.
3. The greedy fit on held-out rows¶
The greedy fit’s held-out likelihood is half a nat worse than its training one (notebook 00). We run the held-out rows through the same blocks.
# Shapes: held_out (N_v) = 1,000
# user
# the greedy fit's states and log-determinants on the held-out rows, (block, held_out, state), (block, held_out)
greedy_held_states: Float[ArrayLike, "block held_out state"]
greedy_held_logdets: Float[ArrayLike, "block held_out"]
greedy_held_states, greedy_held_logdets = run_blocks(greedy_blocks, held_points)
# user
# the input's diagnostics on the held-out rows
input_held: dict = block_diagnostics(held_points[None], np.zeros((1, 1000)))
# user
# the greedy fit's diagnostics on the held-out rows
greedy_held: dict = block_diagnostics(greedy_held_states, greedy_held_logdets)
# user
# the table for the held-out rows
print_table(greedy_blocks, greedy_held, input_held)block type |corr| mean|kurt| KS_max mean log|det J|
input 0.451 1.045 0.159
1 FixedRota 0.046 1.220 0.158 +0.000
2 MixtureGa 0.045 0.081 0.096 +0.510
3 FixedRota 0.029 0.790 0.092 +0.000
4 MixtureGa 0.061 0.601 0.076 +0.169
5 FixedRota 0.004 1.357 0.074 +0.000
6 MixtureGa 0.018 1.033 0.069 +0.099
7 FixedRota 0.062 0.822 0.070 +0.000
8 MixtureGa 0.078 1.268 0.073 +0.008
9 FixedRota 0.021 1.410 0.072 +0.000
10 MixtureGa 0.056 7.950 0.071 +0.024
11 FixedRota 0.159 5.580 0.070 +0.000
12 MixtureGa 0.155 9.908 0.075 -0.002
13 FixedRota 0.039 12.680 0.075 +0.000
14 MixtureGa 0.044 24.638 0.073 +0.043
15 FixedRota 0.227 21.424 0.073 +0.000
16 MixtureGa 0.306 27.837 0.069 +0.025
The bulk of the held-out rows behaves like the training rows: their follows the training curve about 0.01 to 0.02 higher and ends at 0.069, above the 0.055 of a standard normal of their size, and the log-determinants are close to the training ones. The correlation is no longer zero after the rotations, which were fitted to other rows, and grows to 0.31 by the end. The kurtosis does something else: it falls to 0.08 after the first layer, as on the training rows, then climbs: 1.36 at block 5, between 0.8 and 1.4 up to block 9, 7.95 at block 10 and 27.8 at the end.
A kurtosis that large comes from a few points far out. We count the held-out points with a coordinate beyond 4 after each layer, and follow the three with the lowest log-density through the marginal maps, comparing each with the range of the training rows that the marginal map was fitted to.
# Shapes: held_out (N_v) = 1,000
# today (flowjax)
# log p_x(xₙ) of the greedy fit on the held-out rows, (held_out)
greedy_held_logp: Float[ArrayLike, " held_out"] = np.asarray(
jax.vmap(greedy_flow.log_prob)(held_points)
)
# the three held-out rows with the lowest log-density, (held_out)
worst_rows: Float[ArrayLike, " held_out"] = np.argsort(greedy_held_logp)[:3]
print(
f"lowest log p_x: {np.round(greedy_held_logp[worst_rows], 1)}, at {np.round(held_points[worst_rows], 2).tolist()}"
)
print(
"held-out points beyond 4 after each layer:",
[
int((np.abs(greedy_held_states[2 * layer - 1]).max(axis=1) > 4).sum())
for layer in range(1, 9)
],
)lowest log p_x: [-188. -107.5 -88.7], at [[1.350000023841858, -1.5499999523162842], [1.1799999475479126, -1.690000057220459], [1.2699999809265137, -1.600000023841858]]
held-out points beyond 4 after each layer: [0, 4, 5, 6, 8, 6, 8, 7]
for layer in range(1, 9):
# the training rows as they enter the marginal map of this layer, (train, state)
train_entry: Float[ArrayLike, "train state"] = greedy_train_states[2 * layer - 2]
# the three held-out rows as they enter it, (held_out, state)
worst_entry: Float[ArrayLike, "held_out state"] = greedy_held_states[2 * layer - 2][
worst_rows
]
# whether each of the three lies outside the training range in some coordinate, (held_out)
outside: Bool[ArrayLike, " held_out"] = (
(worst_entry < train_entry.min(axis=0))
| (worst_entry > train_entry.max(axis=0))
).any(axis=1)
print(
f"layer {layer}: outside the training range {outside.tolist()}; "
f"largest |coordinate| in {np.round(np.abs(worst_entry).max(axis=1), 1)}, out {np.round(np.abs(greedy_held_states[2 * layer - 1][worst_rows]).max(axis=1), 1)}"
)layer 1: outside the training range [True, True, True]; largest |coordinate| in [2.1 2. 2. ], out [3.5 3.4 3.3]
layer 2: outside the training range [True, True, True]; largest |coordinate| in [2.6 2.6 2.5], out [4.3 4.5 4.2]
layer 3: outside the training range [True, True, True]; largest |coordinate| in [5.1 4.8 4.8], out [5.8 5.2 5.2]
layer 4: outside the training range [True, True, True]; largest |coordinate| in [4.9 5. 4.7], out [5.5 5.6 5.1]
layer 5: outside the training range [True, True, True]; largest |coordinate| in [6.4 5.5 5.5], out [11.2 9. 8.9]
layer 6: outside the training range [True, True, True]; largest |coordinate| in [8.4 7.8 7.2], out [11.2 10.1 9.1]
layer 7: outside the training range [True, True, True]; largest |coordinate| in [12.6 10.8 10.1], out [17. 14.2 13. ]
layer 8: outside the training range [True, True, True]; largest |coordinate| in [15.2 13.3 11.9], out [15.8 13.3 11.7]
The three worst points lie just outside the outer edge of the lower moon, and their log-densities, -188, -107.5 and -88.7, account for 0.38 nats of the held-out mean on their own, most of the half nat by which the held-out NLL exceeds the training one. Each enters every marginal map of the fit outside the range of the training rows that map was fitted to. The first map sends their largest coordinate from about 2 to about 3.4, and the later ones send them further, to between 11.7 and 15.8 by the end, while the number of held-out points beyond 4 grows from none after layer 1 to between 4 and 8. A marginal map fitted to the training rows knows the data only within their range, the boundary problem of Part 3, and a greedy stack compounds it: a point that one layer leaves just outside the range enters the next layer outside its range too.
fig, axes = plt.subplots(1, 3, figsize=(16.5, 4.2))
blocks_axis = np.arange(0, 17)
for diagnostics, start, colour, name in [
(greedy_train, input_train, "C0", "training rows"),
(greedy_held, input_held, "C1", "held-out rows"),
]:
for ax, key in zip(axes, ["corr", "kurtosis", "ks"]):
ax.plot(
blocks_axis,
np.r_[start[key], diagnostics[key]],
"o-",
color=colour,
lw=1.5,
ms=4,
label=name,
)
axes[2].axhline(null_threshold[3000], color="C0", ls=":", lw=1.5)
axes[2].axhline(null_threshold[1000], color="C1", ls=":", lw=1.5)
axes[0].set(ylabel="|correlation|")
axes[1].set(ylabel="mean |excess kurtosis|", yscale="log")
axes[2].set(ylabel="KS_max")
for ax in axes:
ax.set(xlabel="block (0 is the input)")
style_ax(ax)
axes[0].legend()
fig.tight_layout()
plt.show()
Figure 2:The diagnostics after every block of the greedy fit, on the training rows (blue) and the held-out rows (orange): the correlation of the two coordinates, the mean absolute excess kurtosis on a log scale, and KS_max with the 95% quantile of its null distribution for each sample size (dotted). Odd blocks are PCA rotations, even blocks mixture marginal maps.
4. A trained flow, block by block¶
A flow trained by maximum likelihood is fitted as a whole, not layer by layer. We train the cold start of notebook 01, gaussianization_flow with a fixed base, at the peak learning rate that did best there, , with the loop of notebooks 00 and 01.
# Shapes: batch (N_b) = 512
# 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: Float[ArrayLike, ""] = negative_log_likelihood(flow, batch_points)
return loss, {"loss": loss}# today (gauss_flows)
# f_θ, 8 layers of a mixture marginal and a Householder rotation, fixed 𝒩(0, I) base
initial_flow: Transformed = gaussianization_flow(
jr.key(0), n_dims=2, n_layers=8, n_components=8, base_dist=StandardNormal((2,))
)
# today (pipekit)
# the flow as a trainable model; every array of it trains
model_op = EquinoxModelOp(
initial_flow, trainable=jax.tree.map(eqx.is_inexact_array, initial_flow)
)# today (pipekit)
# 3,000 Adam steps on a one-cycle rate that peaks at 3 × 10⁻², gradient clipped to norm 1
loop = TrainingLoop(
model_op,
ArrayDataset(train_points, ()),
optimizer_config={
"name": "adam",
"lr": optax.cosine_onecycle_schedule(3000, 3e-2),
"clip_norm": 1.0,
},
task=FlowNLL(),
max_steps=3000,
batch_size=512,
seed=1,
)# today (pipekit)
# θ after training, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = loop.run()
# today (pipekit)
# the trained flow
trained_flow: Transformed = trained_op.module
# today (flowjax)
# log p_x(xₙ) of the trained flow on the held-out rows, (held_out)
trained_held_logp: Float[ArrayLike, " held_out"] = np.asarray(
jax.vmap(trained_flow.log_prob)(held_points)
)
print(
f"held-out NLL: trained flow {-trained_held_logp.mean():.3f}, greedy fit {-greedy_held_logp.mean():.3f}"
)held-out NLL: trained flow 1.659, greedy fit 2.430
Its eight layers are stored once inside Scan, every array with a leading axis of length 8. eqx.partition splits the layer into those arrays and the rest; indexing the arrays at and combining them with the rest gives layer as an ordinary Chain of a marginal map and a Householder rotation.
# Shapes: the arrays of the Scan carry a leading layer axis of length K = 8
# today (equinox)
# the layer's arrays, stacked over layers, and the rest of the layer
stacked_arrays: eqx.Module
layer_rest: eqx.Module
stacked_arrays, layer_rest = eqx.partition(
trained_flow.bijection.bijection.bijection, eqx.is_inexact_array
)
# today (equinox)
# layer k: the arrays indexed at k, combined with the rest
trained_layers: list = [
eqx.combine(jax.tree.map(lambda array: array[k], stacked_arrays), layer_rest)
for k in range(8)
]
# the 16 blocks in the density direction: each layer's marginal map, then its rotation
trained_blocks: list = [block for layer in trained_layers for block in layer.bijections]
# user
# the trained flow's states and log-determinants on the held-out rows, (block, held_out, state), (block, held_out)
trained_held_states: Float[ArrayLike, "block held_out state"]
trained_held_logdets: Float[ArrayLike, "block held_out"]
trained_held_states, trained_held_logdets = run_blocks(trained_blocks, held_points)print(
f"largest |x_K - f(x)|: {np.abs(trained_held_states[-1] - np.asarray(jax.vmap(trained_flow.bijection.inverse)(held_points))).max():.1e}"
)
# user
# the trained flow's diagnostics on the held-out rows
trained_held: dict = block_diagnostics(trained_held_states, trained_held_logdets)
# user
# the table for the trained flow on the held-out rows
print_table(trained_blocks, trained_held, input_held)largest |x_K - f(x)|: 5.0e-06
block type |corr| mean|kurt| KS_max mean log|det J|
input 0.451 1.045 0.159
1 MixtureGa 0.512 1.302 0.270 -0.763
2 Household 0.402 1.399 0.271 +0.000
3 MixtureGa 0.463 0.521 0.370 +1.100
4 Household 0.282 0.835 0.370 +0.000
5 MixtureGa 0.369 0.808 0.518 +0.478
6 Household 0.008 0.376 0.517 +0.000
7 MixtureGa 0.025 0.701 0.122 +0.076
8 Household 0.161 1.386 0.122 +0.000
9 MixtureGa 0.211 0.727 0.146 -0.344
10 Household 0.167 0.751 0.146 +0.000
11 MixtureGa 0.153 0.516 0.475 +0.553
12 Household 0.151 0.516 0.477 +0.000
13 MixtureGa 0.155 0.337 0.335 +0.143
14 Household 0.027 0.728 0.335 +0.000
15 MixtureGa 0.028 0.115 0.047 -0.063
16 Household 0.006 0.073 0.047 +0.000
The blocks reproduce the trained flow to , float32 rounding of a different order of operations, and its held-out NLL is the 1.659 of notebook 01. Its intermediate states are nothing like a progression towards . rises from 0.16 to 0.52 over the first three layers, falls to 0.12, rises again to 0.48, and drops under the null quantile only at the last layer, to 0.047 against 0.055. Three marginal maps have a negative mean log-determinant, -0.76, -0.34 and -0.06 nats: they squeeze the data, and other layers pay it back with up to +1.10. Nothing in the objective (1) asks an intermediate state to be Gaussian, only the output. The unrolled layers can be inspected exactly like the greedy ones, as the source of this tutorial says, but the reading of section 2, where the work is front-loaded and each layer brings the data closer, does not carry over.
fig = plt.figure(figsize=(17, 8))
top = fig.subplots(1, 5, sharex=True, sharey=True, gridspec_kw={"bottom": 0.55})
for ax, layer in zip(top, [1, 2, 4, 6, 8]):
ax.scatter(
trained_held_states[2 * layer - 1][:, 0],
trained_held_states[2 * layer - 1][:, 1],
color="C2",
**SCATTER_KW,
)
ax.set(title=f"after layer {layer}", xlim=(-4, 4), ylim=(-4, 4))
ax.set_aspect("equal")
style_ax(ax)
bottom = fig.subplots(1, 2, gridspec_kw={"top": 0.45})
bottom[0].plot(
blocks_axis,
np.r_[input_held["ks"], greedy_held["ks"]],
"o-",
color="C1",
lw=1.5,
ms=4,
label="greedy fit",
)
bottom[0].plot(
blocks_axis,
np.r_[input_held["ks"], trained_held["ks"]],
"o-",
color="C2",
lw=1.5,
ms=4,
label="trained flow",
)
bottom[0].axhline(null_threshold[1000], color="k", ls=":", lw=1.5)
bottom[0].set(xlabel="block (0 is the input)", ylabel="KS_max, held-out rows")
bottom[1].bar(
np.arange(1, 17) - 0.2,
greedy_held["logdet"],
width=0.4,
color="C1",
label="greedy fit",
)
bottom[1].bar(
np.arange(1, 17) + 0.2,
trained_held["logdet"],
width=0.4,
color="C2",
label="trained flow",
)
bottom[1].axhline(0, color="k", lw=0.8)
bottom[1].set(xlabel="block", ylabel="mean log|det J|, held-out rows")
for ax in bottom:
ax.legend()
style_ax(ax)
plt.show()
Figure 3:Top: the held-out rows after layers 1, 2, 4, 6 and 8 of the trained flow, each layer a mixture marginal map followed by a Householder rotation. Bottom left: KS_max after every block on the held-out rows, for the greedy fit (orange) and the trained flow (green), with the null quantile for 1,000 points (dotted). Bottom right: each block’s mean log-determinant on the held-out rows.
After its first layer the trained flow has drawn the two moons into the outline of a narrow box; after layer 2 they are a band of clumps, and only by layer 8 a round cloud. The greedy fit’s log-determinants shrink layer by layer and are all positive but one of -0.002; the trained flow’s change sign, and add up to 1.18 nats per held-out point against the greedy fit’s 0.88.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| a flow as a composition of blocks | (1), (2) | Invert(Chain) of fit_rbig, run_blocks |
| the blocks reproduce the log-density | (5) | transform_and_log_det per block |
| per-block diagnostics | (2), (3) | block_diagnostics |
a layer taken out of a Scan | eqx.partition, index the leading axis, eqx.combine |
Next. This completes the diagonal flows of Part 4. Part 5 turns to coupling flows, whose marginal maps take their parameters from the other coordinates.