The 1×1 convolution and ActNorm
Two linear layers that rescale, with log-determinants read off a triangular factor or a diagonal
03 · The 1×1 convolution and ActNorm¶
Notebooks 00_rotation_zoo, 01_householder_orthogonal and 02_fixed_pca_warmstart mix the coordinates with rotations, which preserve volume, so their log-determinant is zero (2). Glow Kingma & Dhariwal, 2018 added two linear layers that rescale as well, so they carry a real log-determinant, but each is stored so that the log-determinant costs rather than the of a dense determinant:
the invertible 1×1 convolution, a learned linear map of the channels stored as the product of two triangular factors;
ActNorm, a per-channel shift and scale whose starting values come from the data.
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 paramax
from flowjax.bijections import 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 DATA_COLOR, style_ax, use_compact_figures
from gauss_flows_maps.bijections import ActNorm1D, Invertible1x1Conv
from gauss_flows_maps.reparam import Reparametrised
from gauss_flows_models.inference import negative_log_likelihood
from gauss_flows_models.info_theory import gaussian_entropy
# Log-determinants and losses get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(0)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "flowjax", "pipekit_train", "gauss_flows_maps")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
flowjax : 19.1.0
pipekit_train : 0.3.4
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 invertible 1×1 convolution¶
An image with positions holds a vector of channels at each position, and a 1×1 convolution applies the same matrix to every one of them,
where is the channel vector at position . It generalises the fixed permutation of the channels that RealNVP placed between coupling layers Dinh et al., 2017: instead of a hard shuffle, a learned mixing. Since the same matrix acts at every position, the Jacobian of the whole image is block diagonal with copies of , and
Invertible1x1Conv stores as the product of a unit lower-triangular and an upper-triangular with a positive diagonal,
so the determinant is the product of the diagonal of ,
which costs . The layer keeps as its free parameter log_diag_u, and the off-diagonal entries of both factors as lower_off and upper_off. A new layer starts near the identity, so we set all three by hand to get a matrix worth looking at.
# Shapes: state (D_x) = 4, the channels
PerState = Float[ArrayLike, " state"]
# log U_dd, (state)
log_diag: PerState = jnp.array([0.5, -0.3, 0.2, 0.1])
PerOffDiagonal = Float[ArrayLike, " off_diagonal"]
# the 6 entries below the diagonal of L, (off_diagonal)
lower_entries: PerOffDiagonal = 0.5 * jr.normal(jr.key(1), (6,))
# the 6 entries above the diagonal of U, (off_diagonal)
upper_entries: PerOffDiagonal = 0.5 * jr.normal(jr.key(2), (6,))The header of the cell above declares off_diagonal, the entries strictly below or above a diagonal. We put them into a fresh layer.
# Shapes: off_diagonal = 6 entries of a strict triangle
# today (gauss_flows)
# A = L U, near the identity at first
conv: Invertible1x1Conv = Invertible1x1Conv(jr.key(0), n_channels=4)
# today (gauss_flows)
# A = L U with our log U_dd and off-diagonal entries
conv: Invertible1x1Conv = eqx.tree_at(
lambda layer: (layer.log_diag_u, layer.lower_off, layer.upper_off),
conv,
(log_diag, lower_entries, upper_entries),
)We read back from the layer, as the images of the basis vectors, and compare the layer’s log-determinant with (4) and with the dense determinant.
StateMatrix = Float[ArrayLike, "state state"]
# today (gauss_flows)
# A eⱼ for each basis vector eⱼ, as rows, (state, state)
images: StateMatrix = jax.vmap(conv.transform)(jnp.eye(4))
# A, with the images as columns, (state, state)
matrix: StateMatrix = images.T
# x, one channel vector, (state)
channels: PerState = jr.normal(jr.key(3), (4,))
latent: PerState
layer_logdet: Float[ArrayLike, ""]
# today (gauss_flows)
# z = A x and log |det A|, (state)
latent, layer_logdet = conv.transform_and_log_det(channels)
# today (gauss_flows)
# x̂ = A⁻¹ z, (state)
recovered: PerState = conv.inverse(latent)The three log-determinants and the round trip:
Scalar = Float[ArrayLike, ""]
# ∑_d log U_dd
formula_logdet: Scalar = jnp.sum(log_diag)
# log |det A|, from a dense LU factorisation with pivoting
dense_logdet: Scalar = jnp.linalg.slogdet(matrix)[1]
# max_d |x̂_d − x_d|
round_trip: Scalar = jnp.max(jnp.abs(recovered - channels))
print(f"layer log_det : {float(layer_logdet):+.6f}")
print(f"sum of log U_dd : {float(formula_logdet):+.6f}")
print(f"dense log|det A| : {float(dense_logdet):+.6f}")
print(f"round trip error : {float(round_trip):.1e}")layer log_det : +0.500000
sum of log U_dd : +0.500000
dense log|det A| : +0.500000
round trip error : 1.1e-16
On an image the layer acts on each position’s channel vector, so we vmap it over the positions of an 8 × 8 image and add up the log-determinants.
# Shapes: row = 8; column = 8; position (P) = 64 = 8 × 8
# an 8 × 8 image of 4 channels, (row, column, state)
image: Float[ArrayLike, "row column state"] = jr.normal(jr.key(4), (8, 8, 4))
PositionState = Float[ArrayLike, "position state"]
# one channel vector per position, (position, state)
pixels: PositionState = image.reshape(64, 4)
image_latent: PositionState
position_logdets: Float[ArrayLike, " position"]
# today (gauss_flows)
# z_p = A x_p and log |det A| at each position p, (position, state), (position)
image_latent, position_logdets = jax.vmap(conv.transform_and_log_det)(pixels)
print(f"sum over positions : {float(jnp.sum(position_logdets)):.4f}")
print(f"P log|det A| : {64 * float(layer_logdet):.4f}")sum over positions : 32.0000
P log|det A| : 32.0000
The layer’s log-determinant is (4) exactly, it agrees with the dense determinant, the inverse recovers the input to machine precision, and over the image it adds up to (2). Figure 1 shows the two factors and their product. Only the log-determinant is cheap: Invertible1x1Conv.inverse solves a dense linear system with , which costs .
lower_factor = np.eye(4)
lower_factor[np.tril_indices(4, k=-1)] = lower_entries
upper_factor = np.diag(np.exp(log_diag))
upper_factor[np.triu_indices(4, k=1)] = upper_entries
fig, axes = plt.subplots(1, 3, figsize=(10, 3.2))
factors = [lower_factor, upper_factor, np.asarray(matrix)]
for ax, factor, name in zip(axes, factors, ["L", "U", "A = L U"], strict=True):
shown = ax.imshow(factor, cmap="RdBu_r", vmin=-2, vmax=2)
ax.set(title=name, xticks=range(4), yticks=range(4))
fig.colorbar(shown, ax=axes, fraction=0.02)
plt.show()
Figure 1:The 1×1 convolution’s matrix (right) is stored as a unit lower-triangular (left) times an upper-triangular with a positive diagonal (middle). Its log-determinant is the sum of the log-diagonal of .
2. Which matrices the LU form reaches¶
Storing as with a positive diagonal makes it invertible by construction, whatever the parameters: , so no gradient step can make it singular. The price is that not every invertible matrix has this form. An LU factorisation without row exchanges and with positive pivots exists exactly when every leading principal minor, the determinant of the top-left block, is positive. That rules out every matrix with , a reflection for instance, and also matrices such as the 90° rotation, whose top-left entry is zero.
Minors = Float[ArrayLike, " minor"]
# user
# det of the top-left k × k block of A, for k = 1, …, D_x
def leading_minors(square: StateMatrix) -> Minors:
"""The leading principal minors of ``square``."""
# det A_{1:k, 1:k} for each k, (minor)
return np.array([np.linalg.det(square[:k, :k]) for k in range(1, len(square) + 1)])We check three 2 × 2 matrices and the layer’s own.
# Shapes: minor = D_x leading principal minors
candidates = {
"90° rotation": np.array([[0.0, -1.0], [1.0, 0.0]]),
"reflection": np.array([[1.0, 0.0], [0.0, -1.0]]),
"30° rotation": np.array([[0.87, -0.5], [0.5, 0.87]]),
"the layer's A": np.asarray(matrix),
}
for name, square in candidates.items():
# user
# the leading principal minors, (minor)
minors: Minors = leading_minors(square)
print(
f"{name:14s} minors {np.round(minors, 3)}, reachable: {bool(np.all(minors > 0))}"
)90° rotation minors [0. 1.], reachable: False
reflection minors [ 1. -1.], reachable: False
30° rotation minors [0.87 1.007], reachable: True
the layer's A minors [1.649 1.221 1.492 1.649], reachable: True
Every matrix near the identity has positive leading minors, and a layer starts at the identity, so this limit rarely bites in training. Glow keeps a fixed permutation in front of the factors, , and lets the diagonal of take either sign with a fixed sign pattern Kingma & Dhariwal, 2018; LULinearPermute in gauss_flows adds the permutation and keeps the diagonal positive.
3. Training keeps it invertible¶
We train the 1×1 convolution as a flow on its own, by maximum likelihood. The data are 2,000 vectors of four correlated coordinates, centred, so the best a linear flow with a standard normal base can do is to whiten them. Its negative log-likelihood is then the entropy of the Gaussian fit, , from (2).
# Shapes: sample (N) = 2,000; state (D_x) = 4
# a random mixing matrix, (state, state)
mixing: StateMatrix = rng.standard_normal((4, 4))
SampleState = Float[ArrayLike, "sample state"]
# x = M w ⊙ (3, 0.5, 2, 1) for w ~ 𝒩(0, I), (sample, state)
correlated: SampleState = (
rng.standard_normal((2000, 4)) @ mixing.T * np.array([3.0, 0.5, 2.0, 1.0])
)
# x − x̄, centred, (sample, state)
centred: SampleState = correlated - correlated.mean(axis=0)
# today (gauss_flows)
# ½ log det(2πe Σ̂_x), the Gaussian fit's negative log-likelihood
gaussian_nll: float = gaussian_entropy(np.cov(centred.T, bias=True))The flow has a standard normal base and the 1×1 convolution as its map from data to latent, so flowjax’s Transformed takes its inverse as the map from latent to data.
# today (gauss_flows)
# z = A x with A near the identity
start_conv = Invertible1x1Conv(jr.key(0), n_channels=4)
# today (flowjax)
# p_x(x) = 𝒩(A x; 0, I) |det A|
linear_flow = Transformed(StandardNormal((4,)), Invert(start_conv))
Batch = Float[ArrayLike, "batch state"]
# 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ₙ; θ) over a batch of N_b points, also logged
def loss_fn(self, flow, batch, key):
# the points of the batch; its targets are empty, (batch, state)
batch_points: Batch
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}We train on the whole data set as one batch, with Adam at a learning rate of 10-2 for 1,500 steps.
# Shapes: batch (N_b) = 2,000, the whole data set
# today (pipekit)
# the per-step training losses
history = History()
# today (pipekit)
# Adam on 𝓛(θ), full batch
loop = TrainingLoop(
EquinoxModelOp(linear_flow),
ArrayDataset(centred, ()),
task=FlowNLL(),
optimizer_config={"name": "adam", "lr": 1e-2},
max_steps=1500,
batch_size=2000,
log_every_n_steps=500,
callbacks=(history,),
)We run it and take the trained 1×1 convolution out of the flow.
# today (pipekit)
# θ̂ = argmin_θ 𝓛(θ)
trained_op: EquinoxModelOp
trained_op, _ = loop.run()
# today (flowjax)
# the trained flow, and the 1×1 convolution inside its inverse
trained_conv: Invertible1x1Conv = trained_op.module.bijection.bijection
PerStep = Float[ArrayLike, " step"]
# 𝓛(θ) at every step, (step)
step_losses: PerStep = np.array([metrics["loss"] for _, metrics in history.train])We check the trained layer the same way as in section 1, and look at the covariance of its output.
# Shapes: step = 1,500 training steps
# today (gauss_flows)
# A eⱼ for each basis vector eⱼ, transposed to A, (state, state)
trained_matrix: StateMatrix = jax.vmap(trained_conv.transform)(jnp.eye(4)).T
# today (gauss_flows)
# z = A x for every sample, (sample, state)
trained_latent: SampleState = jax.vmap(trained_conv.transform)(centred)
# today (gauss_flows)
# x̂ = A⁻¹ z for every sample, (sample, state)
trained_recovered: SampleState = jax.vmap(trained_conv.inverse)(trained_latent)
print(f"final NLL {step_losses[-1]:.4f}, Gaussian fit {gaussian_nll:.4f}")
print(
f"layer log_det {float(jnp.sum(trained_conv.log_diag_u)):+.4f}, dense {float(jnp.linalg.slogdet(trained_matrix)[1]):+.4f}"
)
print(
f"det A = {float(jnp.linalg.det(trained_matrix)):.4f}, round trip {float(jnp.max(jnp.abs(trained_recovered - centred))):.1e}"
)
print(
"covariance of z:\n", np.round(np.cov(np.asarray(trained_latent).T, bias=True), 3)
)final NLL 7.4155, Gaussian fit 7.4155
layer log_det -1.7398, dense -1.7398
det A = 0.1756, round trip 3.6e-15
covariance of z:
[[ 1. 0. 0. -0.]
[ 0. 1. -0. -0.]
[ 0. -0. 1. -0.]
[-0. -0. -0. 1.]]
fig, ax = plt.subplots(figsize=(6, 3.5))
ax.plot(step_losses, color=DATA_COLOR, lw=1.5, label="1x1 convolution")
ax.axhline(gaussian_nll, color="k", ls="--", lw=1.2, label="Gaussian fit")
ax.set(xlabel="step", ylabel="negative log-likelihood (nats)")
ax.legend()
style_ax(ax)
plt.show()
Figure 2:The negative log-likelihood of the 1×1 convolution over 1,500 Adam steps falls to the entropy of the Gaussian fit (dashed), the best any linear flow with a standard normal base can do.
The trained layer reaches the Gaussian fit to four decimals and whitens the data, its output covariance is the identity to three decimals, its log-determinant still equals the dense one, and stays positive with an exact inverse. The LU form keeps the layer a valid bijection throughout training at no cost.
4. ActNorm¶
ActNorm is a per-channel shift and scale,
with a location and a positive scale . Its Jacobian is diagonal, so
times on an image, where the same acts at every position. gauss_flows keeps each positive through a Reparametrised leaf, starting at with .
What gives ActNorm its name is the data-dependent initialisation Kingma & Dhariwal, 2018: before training, set to the mean of a batch and each to its standard deviation,
so the layer’s output starts with zero mean and unit variance in every channel. ActNorm has no from_data constructor yet (gauss_flows#112), so we write one.
# Shapes: sample (N) = 2,000; state (D_x) = 4
# user
# b = x̄ and s_d² = (1/N) ∑ₙ (x_{n,d} − b_d)², an ActNorm1D started from the data
def actnorm_from_data(batch: SampleState) -> ActNorm1D:
"""An ``ActNorm1D`` whose output on ``batch`` has zero mean and unit variance."""
# today (gauss_flows)
# s_d = 10⁻⁵ + softplus(·), the layer's own constraint
positive_scale = Reparametrised("softplus", lower=1e-5)
# today (gauss_flows)
# b = 0, s = 0.693 at first
layer = ActNorm1D(shape=(batch.shape[1],))
# today (gauss_flows)
# b = x̄ and s_d = the standard deviation of channel d
return eqx.tree_at(
lambda layer: (layer.loc, layer.scale),
layer,
(jnp.mean(batch, axis=0), positive_scale.parameter(jnp.std(batch, axis=0))),
)We test it on channels with very different offsets and scales, and compare the starting negative log-likelihood of a flow with a default ActNorm and with a data-initialised one.
# x_d ~ 𝒩(b_d, s_d²) with b = (5, −2, 0, 1) and s = (3, 0.5, 2, 1), (sample, state)
raw: SampleState = jnp.asarray(
rng.standard_normal((2000, 4)) * np.array([3.0, 0.5, 2.0, 1.0])
+ np.array([5.0, -2.0, 0.0, 1.0])
)
# user
# b = x̄, s = the per-channel standard deviation
started: ActNorm1D = actnorm_from_data(raw)
# today (gauss_flows)
# z = diag(s)⁻¹ (x − b) for every sample, (sample, state)
standardised: SampleState = jax.vmap(paramax.unwrap(started).transform)(raw)
# today (flowjax, gauss_flows)
# 𝓛 of a flow with a default ActNorm
default_nll: Scalar = negative_log_likelihood(
Transformed(StandardNormal((4,)), Invert(ActNorm1D(shape=(4,)))), raw
)
# today (flowjax, gauss_flows)
# 𝓛 of a flow with the data-initialised ActNorm
started_nll: Scalar = negative_log_likelihood(
Transformed(StandardNormal((4,)), Invert(started)), raw
)The best a per-channel shift and scale can do is the diagonal Gaussian fit, whose negative log-likelihood is with from (7).
# today (gauss_flows)
# ½ ∑_d log(2πe s_d²), the diagonal Gaussian fit's negative log-likelihood
diagonal_nll: float = gaussian_entropy(np.diag(np.var(np.asarray(raw), axis=0)))
print(f"output mean {np.round(np.asarray(standardised.mean(axis=0)), 3)}")
print(f"output std {np.round(np.asarray(standardised.std(axis=0)), 3)}")
print(f"NLL with a default ActNorm : {float(default_nll):.4f}")
print(f"NLL with a data-initialised one : {float(started_nll):.4f}")
print(f"NLL of the diagonal Gaussian fit : {diagonal_nll:.4f}")output mean [-0. -0. 0. 0.]
output std [1. 1. 1. 1.]
NLL with a default ActNorm : 48.7159
NLL with a data-initialised one : 6.7398
NLL of the diagonal Gaussian fit : 6.7398
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8), sharey=True)
for channel in range(4):
axes[0].hist(
np.asarray(raw[:, channel]), bins=50, alpha=0.5, label=f"channel {channel + 1}"
)
axes[1].hist(
np.asarray(standardised[:, channel]),
bins=50,
alpha=0.5,
label=f"channel {channel + 1}",
)
axes[0].set(xlabel="$x_d$", ylabel="count", title="Raw channels")
axes[1].set(xlabel="$z_d$", title="After a data-initialised ActNorm")
for ax in axes:
ax.legend(fontsize=8)
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 3:Left: four channels with offsets 5, −2, 0 and 1 and scales 3, 0.5, 2 and 1. Right: the same channels after a data-initialised ActNorm, each with zero mean and unit variance.
The data-initialised layer starts at the diagonal Gaussian fit to every digit printed, about 6.74 nats against 48.7 for the default, whose single scale of 0.693 ignores the offsets and the scales of the channels. Glow used this initialisation so that every layer of a deep stack starts with well-scaled inputs Kingma & Dhariwal, 2018; with it, training begins from the best per-channel affine fit rather than far from it.
5. How the layers fit together¶
A step of Glow chains ActNorm, a 1×1 convolution and a coupling layer, and their log-determinants add (4). The rotations of notebooks 00_rotation_zoo to 02_fixed_pca_warmstart can take the place of the 1×1 convolution: the choice is between a map that only rotates and costs nothing, and one that also rescales and costs the sum of a triangular diagonal.
Recap¶
| Layer | Equation | Log-determinant | Kept valid by | In code |
|---|---|---|---|---|
| rotation | (1) | 0, (2) | an orthogonal parametrisation | HouseholderRotation, OrthogonalRotation, FixedRotation |
| 1×1 convolution | (1), (3) | , (2), (4) | the LU form, positive leading minors | Invertible1x1Conv, LULinearPermute |
| ActNorm | (5) | , (6) | a positive scale, data initialisation (7) | ActNorm, ActNorm1D |
Next. With marginal maps from Part 1 and the linear layers of Part 2, Part 3 assembles the classic algorithm that alternates them until the data are Gaussian: Rotation-Based Iterative Gaussianization, the loop of marginal passes and rotations whose convergence 00_rotation_zoo previewed.
- Kingma, D. P., & Dhariwal, P. (2018). Glow: Generative Flow with Invertible 1x1 Convolutions. Advances in Neural Information Processing Systems (NeurIPS).
- Dinh, L., Sohl-Dickstein, J., & Bengio, S. (2017). Density Estimation using Real NVP. International Conference on Learning Representations (ICLR).