Hutchinson's trace estimator
One Jacobian-vector product per probe instead of one per dimension: an unbiased trace whose error falls as one over the square root of the number of probes
01 · Hutchinson’s trace estimator¶
The log-density of a continuous flow (4) integrates the trace of the vector field’s Jacobian along the path, and the ODE solver asks for that trace at every step. Notebook 00 computed it exactly, with one Jacobian-vector product per dimension: two in 2-D, but thousands for an image. Hutchinson’s estimator Hutchinson, 1990 needs one product per random probe, whatever the dimension, and it is what FFJORD Grathwohl et al., 2019 uses to scale. It trades the exact value for an unbiased estimate with a variance, and this notebook measures that variance where it matters.
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 time
from collections.abc import Callable
import gaussx
import jax
import jax.numpy as jnp
import jax.random as jr
import lineax as lx
import matplotlib.pyplot as plt
import numpy as np
import optax
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Float, Key
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,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
from gauss_flows_models.flows import FFJORD, DiffeqMLP
from gauss_flows_models.inference import negative_log_likelihood
np.set_printoptions(precision=3, suppress=True)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark(
"jax", "numpy", "gaussx", "lineax", "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
gaussx : 0.8.4
lineax : 0.1.1
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 notebook runs in float32, the precision users get by default.
The estimator¶
Let be a random probe with zero mean and identity covariance, . For any square matrix , , so
and the average over independent probes is an unbiased estimate of the trace:
The estimate never needs itself, only the products . For the Jacobian of a vector field, is one forward-mode Jacobian-vector product, so probes cost products against the of the exact trace. Two probe distributions are common: Rademacher probes, whose entries are with equal probability, and standard-normal probes.
gaussx.trace implements both, and it is what FFJORD calls: stochastic=True with algorithm="hutchinson" gives (2), and sampler picks the probes ("signs" for Rademacher, "normal" for Gaussian). We use it throughout rather than writing the estimator again.
1. A known matrix¶
We start where the answer is known: a random symmetric matrix with , wrapped as a lineax operator so that gaussx sees only its matrix-vector products.
# Shapes: state (D_x) = 24
StateMatrix = Float[ArrayLike, "state state"]
Scalar = Float[ArrayLike, ""]
# today (jax)
# M ~ N(0, I), a random square matrix, (state, state)
raw_matrix: StateMatrix = jr.normal(jr.key(0), (24, 24))
# A = (M + Mᵀ) / 2, symmetric, (state, state)
matrix: StateMatrix = 0.5 * (raw_matrix + raw_matrix.T)
# today (lineax)
# A as an operator, seen only through its products A ε
matrix_op: lx.MatrixLinearOperator = lx.MatrixLinearOperator(matrix)
# today (gaussx)
# tr(A), from the diagonal of the materialised matrix
exact_trace: float = float(gaussx.trace(matrix_op))# user
# tr̂(A) from N_p probes drawn from `key`
def estimate(
key: Key[jax.Array, ""],
num_probes: int,
sampler: str = "signs",
algorithm: str = "hutchinson",
) -> Scalar:
"""A stochastic estimate of tr(A) with ``num_probes`` probes."""
# today (gaussx)
# (1/N_p) ∑ᵢ εᵢᵀ A εᵢ, for algorithm="hutchinson"
return gaussx.trace(
matrix_op,
stochastic=True,
num_probes=num_probes,
key=key,
sampler=sampler,
algorithm=algorithm,
)We draw 4000 estimates with a single Rademacher probe each.
# Shapes: trial = 4,000 independent estimates
PerTrial = Float[ArrayLike, " trial"]
# one key per trial, (trial)
trial_keys: Key[jax.Array, " trial"] = jr.split(jr.key(1), 4000)
# user
# εᵀ A ε for one Rademacher probe per trial, (trial)
single_rademacher: PerTrial = jax.vmap(lambda key: estimate(key, 1))(trial_keys)
# the standard error of the mean of the 4,000 estimates
mean_error: float = float(single_rademacher.std() / np.sqrt(4000))
print(f"tr(A) = {exact_trace:.3f}")
print(
f"mean of 4,000 one-probe estimates = {float(single_rademacher.mean()):.3f} +/- {mean_error:.3f}"
)
print(f"spread of one estimate = {float(single_rademacher.std()):.2f}")tr(A) = -1.781
mean of 4,000 one-probe estimates = -2.032 +/- 0.361
spread of one estimate = 22.85
The mean of the one-probe estimates, , is within one standard error of : the estimator is unbiased. One estimate alone is of little use here, though: its spread is 22.9, more than ten times the trace.
Averaging probes divides the variance by , so the root-mean-square error should fall as . We measure it over 400 repeats for from 1 to 256.
# Shapes: repeat = 400 repeats; probe_count = 9 probe counts
PerCount = Float[ArrayLike, " probe_count"]
# one key per repeat, (repeat)
repeat_keys: Key[jax.Array, " repeat"] = jr.split(jr.key(2), 400)
# user
# √(mean (tr̂ − tr)²) over the 400 repeats
def rmse_of(
num_probes: int, sampler: str = "signs", algorithm: str = "hutchinson"
) -> float:
"""The root-mean-square error of the estimate over 400 repeats."""
# user
# tr̂(A) of each repeat, (repeat)
estimates: Float[ArrayLike, " repeat"] = jax.vmap(
lambda key: estimate(key, num_probes, sampler, algorithm)
)(repeat_keys)
return float(jnp.sqrt(jnp.mean((estimates - exact_trace) ** 2)))# the probe counts N_p
probe_counts: list = [1, 2, 4, 8, 16, 32, 64, 128, 256]
# user
# the RMSE of Rademacher probes at each N_p, (probe_count)
rademacher_rmse: PerCount = np.array([rmse_of(count) for count in probe_counts])
# user
# the RMSE of Gaussian probes at each N_p, (probe_count)
gaussian_rmse: PerCount = np.array([rmse_of(count, "normal") for count in probe_counts])
print(f"Rademacher RMSE: {rademacher_rmse}")
print(f"Gaussian RMSE : {gaussian_rmse}")Rademacher RMSE: [23.158 16.121 11.633 8.127 5.651 4.063 2.934 2.015 1.402]
Gaussian RMSE : [23.055 16.809 11.764 8.136 5.727 4.199 3.012 2.054 1.455]
fig, (ax_hist, ax_rmse) = plt.subplots(1, 2, figsize=(12, 4.2))
ax_hist.hist(np.asarray(single_rademacher), bins=60, color=DATA_COLOR, alpha=0.7)
ax_hist.axvline(exact_trace, color="k", ls="--", lw=1.5, label="tr(A)")
ax_hist.set(xlabel="one-probe estimate", ylabel="count", title="one Rademacher probe")
ax_hist.legend()
ax_rmse.loglog(
probe_counts, rademacher_rmse, "o-", color=DATA_COLOR, label="Rademacher"
)
ax_rmse.loglog(probe_counts, gaussian_rmse, "s-", color=LATENT_COLOR, label="Gaussian")
ax_rmse.loglog(
probe_counts,
rademacher_rmse[0] / np.sqrt(probe_counts),
"k:",
label="$1/\\sqrt{N_p}$",
)
ax_rmse.set(
xlabel="probes $N_p$", ylabel="RMSE of the estimate", title="error against probes"
)
ax_rmse.legend()
style_ax(ax_hist)
style_ax(ax_rmse)
plt.show()
Figure 1:Hutchinson’s estimator on a random symmetric 24 × 24 matrix. Left: 4,000 estimates with one Rademacher probe each, centred on the exact trace (dashed). Right: the error over 400 repeats against the number of probes, for Rademacher and Gaussian probes, with a line falling as one over the square root of the count (dotted).
Both lines fall as , from 23 at one probe to 1.4 at 256. Halving the error costs four times the probes, so the estimate is cheap only when a rough value will do.
2. Rademacher or Gaussian probes¶
For a symmetric the variance of one probe’s estimate has a closed form for each distribution:
A Rademacher probe has exactly, so the diagonal of enters every estimate with weight one and contributes no variance; only the off-diagonal entries do. A Gaussian probe has random, and the diagonal adds its own share. Rademacher probes are never worse, and much better for a matrix whose mass sits on the diagonal. We check both formulas against the variance of 4000 one-probe estimates.
# 2(‖A‖_F² − ∑_d A_dd²), the variance of one Rademacher probe
rademacher_variance: float = float(
2 * ((matrix**2).sum() - (jnp.diag(matrix) ** 2).sum())
)
# 2 ‖A‖_F², the variance of one Gaussian probe
gaussian_variance: float = float(2 * (matrix**2).sum())
# user
# εᵀ A ε for one Gaussian probe per trial, (trial)
single_gaussian: PerTrial = jax.vmap(lambda key: estimate(key, 1, "normal"))(trial_keys)
print(
f"Rademacher: formula {rademacher_variance:.1f}, sampled {float(single_rademacher.var()):.1f}"
)
print(
f"Gaussian : formula {gaussian_variance:.1f}, sampled {float(single_gaussian.var()):.1f}"
)Rademacher: formula 536.4, sampled 522.1
Gaussian : formula 571.2, sampled 556.6
Both formulas match the sampled variances to within 3 %, about the sampling error of a variance from 4000 draws. For this matrix the two probes are almost equally good: its diagonal holds 6 % of , so removing the diagonal’s share changes the variance by that much, and the two RMSE lines above nearly coincide.
gaussx.trace also offers two estimators that spend part of their budget on a low-rank sketch of and take that part’s trace exactly: Hutch++ (algorithm="hutchpp", whose num_probes is its whole budget of products) and XTrace (algorithm="xtrace", two products per probe, with probes on the sphere). They pay off when the spectrum of decays. We compare the three at the same number of matrix-vector products.
# the budgets of matrix-vector products
budgets: list = [6, 12, 24]
for budget in budgets:
# user
# the RMSE of Hutchinson with `budget` probes
hutchinson_rmse: float = rmse_of(budget)
# user
# the RMSE of Hutch++ with a budget of `budget` products
hutchpp_rmse: float = rmse_of(budget, "signs", "hutchpp")
# user
# the RMSE of XTrace with budget / 2 probes of two products each
xtrace_rmse: float = rmse_of(budget // 2, "sphere", "xtrace")
print(
f"{budget:2d} products: Hutchinson {hutchinson_rmse:.2f}, Hutch++ {hutchpp_rmse:.2f}, XTrace {xtrace_rmse:.2e}"
) 6 products: Hutchinson 9.42, Hutch++ 14.08, XTrace 1.25e+01
12 products: Hutchinson 6.43, Hutch++ 7.97, XTrace 7.64e+00
24 products: Hutchinson 4.82, Hutch++ 3.93, XTrace 0.00e+00
On this matrix neither sketch pays off below a budget of products. Hutch++ is worse than Hutchinson at 6 and 12 products and better only at 24, and XTrace is worse at 6 and 12 but exact at 24, because its 12 probes then span all of and the sketch holds the whole matrix. The spectrum of a random symmetric matrix does not decay, so there is no low-rank part to take out. FFJORD offers only Hutchinson.
3. Inside FFJORD: the divergence at one step¶
The matrix FFJORD needs is the Jacobian of its vector field, and the estimate enters at every solver step. To see the error on a Jacobian a flow actually produces, we train a FFJORD on a 6-D toy: Gaussian draws , bent coordinate by coordinate to and mixed by a random rotation, then standardised. There are training rows and held-out rows.
# Shapes: sample (N) = 1,500; state (D_x) = 6; train (N_t) = 1,200; held_out (N_v) = 300
SampleState = Float[ArrayLike, "sample state"]
HeldState = Float[ArrayLike, "held_out state"]
# today (jax)
# u ~ N(0, I), (sample, state)
gauss_draws: SampleState = jr.normal(jr.key(3), (1500, 6))
# today (jax)
# a random rotation Q, the orthogonal factor of a Gaussian matrix, (state, state)
rotation: StateMatrix = jnp.linalg.qr(jr.normal(jr.key(4), (6, 6)))[0]
# x = (u + 0.6 sin 2u) Qᵀ, a bent Gaussian with mixed coordinates, (sample, state)
bent: SampleState = (gauss_draws + 0.6 * jnp.sin(2 * gauss_draws)) @ rotation.T
# standardised per coordinate, in float32, (sample, state)
samples: SampleState = np.asarray(
(bent - bent.mean(axis=0)) / bent.std(axis=0), dtype=np.float32
)
# the training rows, (train, state)
train_points: Float[ArrayLike, "train state"] = samples[:1200]
# the held-out rows, (held_out, state)
held_points: HeldState = samples[1200:]We train with the exact trace, six products per solver step. FFJORD’s default, divergence_mode="hutchinson" with one probe, is how a high-dimensional FFJORD would be trained, but today it does not train: section 6 shows why. The loop is notebook 00’s: Adam with a one-cycle cosine learning rate that peaks at , the gradient clipped to a global norm of 1, 300 steps of 256 rows.
# Shapes: batch (N_b) = 256
# 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}# Shapes: step = 300 training steps
# today (optax)
# the learning rate of each step: up to 5 × 10⁻³, then down to almost zero
schedule: optax.Schedule = optax.cosine_onecycle_schedule(
transition_steps=300, peak_value=5e-3
)
# user
# the settings of the run: Adam with the gradient clipped to a global norm of 1
loop_settings: dict = {
"optimizer_config": {"name": "adam", "lr": schedule, "clip_norm": 1.0},
"task": FlowNLL(),
"max_steps": 300,
"steps_per_epoch": 50,
"log_every_n_steps": 50,
"batch_size": 256,
"seed": 1,
}# user
# v_θ̂ after the run from `ffjord`, and the training time in seconds
def train_field(ffjord: FFJORD) -> tuple[DiffeqMLP, float]:
"""Train ``ffjord`` on a standard-normal base and return its vector field."""
# the clock before training
start: float = time.perf_counter()
# today (pipekit)
# θ̂ after the run, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = TrainingLoop(
EquinoxModelOp(Transformed(StandardNormal((6,)), ffjord)),
ArrayDataset(train_points, ()),
callbacks=(History(),),
**loop_settings,
).run()
return trained_op.module.bijection.vector_field, time.perf_counter() - start# user
# the FFJORD of `field` with the trace exact or from the probes of jr.key(seed), solved to 10⁻⁵
def ffjord_of(
field: DiffeqMLP, mode: str = "exact", num_probes: int = 1, seed: int = 0
) -> FFJORD:
"""A FFJORD around ``field`` with the given trace."""
# today (gauss_flows)
# the field, with its probes from jr.key(seed)
return FFJORD(
jr.key(seed),
shape=(6,),
vector_field=field,
divergence_mode=mode,
n_hutchinson_samples=num_probes,
)PerHeld = Float[ArrayLike, " held_out"]
# user
# log p_x(xₙ) of `rows` under `field`, with the trace exact or from the probes of jr.key(seed)
def log_density(field: DiffeqMLP, rows: HeldState, *trace) -> PerHeld:
"""The log-density of ``rows`` under ``field``; ``trace`` is passed to ``ffjord_of``."""
# user
# the flow p_x with a standard-normal base
flow: Transformed = Transformed(StandardNormal((6,)), ffjord_of(field, *trace))
# today (flowjax)
# log p_x(xₙ) at each row, (held_out)
return jax.jit(jax.vmap(flow.log_prob))(rows)# today (gauss_flows)
# v_θ(t, x), an MLP of [t, x] with two hidden layers of 64 tanh units
vector_field: DiffeqMLP = DiffeqMLP(jr.key(5), in_dim=6, control_dim=0, hidden=(64, 64))
# today (gauss_flows)
# the ODE flow with the exact trace, solved to 10⁻⁴
exact_ffjord: FFJORD = FFJORD(
jr.key(6),
shape=(6,),
vector_field=vector_field,
divergence_mode="exact",
rtol=1e-4,
atol=1e-4,
)# user
# v_θ̂ and the training time
trained_field: DiffeqMLP
train_seconds: float
trained_field, train_seconds = train_field(exact_ffjord)
# user
# −(1/N_v) ∑ₙ log p_x(xₙ) on the held-out rows before training
initial_nll: float = -float(log_density(vector_field, held_points).mean())
# user
# −(1/N_v) ∑ₙ log p_x(xₙ; θ̂) on the held-out rows after training
held_nll: float = -float(log_density(trained_field, held_points).mean())
print(
f"training took {train_seconds / 60:.1f} min; held-out NLL {initial_nll:.3f} before, {held_nll:.3f} after"
)training took 0.8 min; held-out NLL 8.552 before, 6.921 after
Training takes about a minute and lowers the held-out NLL from 8.55 to 6.92 nats. The fit is not the point here; what we need is a Jacobian that a trained flow produces.
The divergence at one step is the trace of . We compute it at the way FFJORD does: a lineax JacobianLinearOperator of the vector field, applied by forward-mode products, and gaussx.trace of it, exact or from probes.
# user
# div v(t, x) = tr(J_v(t, x)), exact when num_probes is 0, else from num_probes probes
def divergence(field, point, time_t=0.5, num_probes=0, key=None) -> Scalar:
"""The divergence of ``field`` at ``(time_t, point)``, as FFJORD computes it."""
# today (lineax)
# J_v(t, x), applied by forward-mode Jacobian-vector products
jacobian: lx.JacobianLinearOperator = lx.JacobianLinearOperator(
lambda state, _: field(time_t, state, None), point, jac="fwd"
)
if num_probes == 0:
# today (gaussx)
# tr(J_v), from the Jacobian materialised by D_x products
return gaussx.trace(jacobian)
# today (gaussx)
# (1/N_p) ∑ᵢ εᵢᵀ J_v εᵢ, one product per probe
return gaussx.trace(
jacobian,
stochastic=True,
num_probes=num_probes,
key=key,
algorithm="hutchinson",
)We evaluate it at the 300 held-out rows, exactly and with 1 and 16 probes, with a fresh key at each row so that the errors are independent draws.
# one key per held-out row, (held_out)
row_keys: Key[jax.Array, " held_out"] = jr.split(jr.key(7), 300)
# user
# tr(J_v(0.5, xₙ)) at each held-out row, (held_out)
exact_div: PerHeld = jax.vmap(lambda point: divergence(trained_field, point))(
held_points
)
# user
# the estimate with one probe at each row, (held_out)
one_probe_div: PerHeld = jax.vmap(
lambda point, key: divergence(trained_field, point, 0.5, 1, key)
)(held_points, row_keys)
# user
# the estimate with 16 probes at each row, (held_out)
sixteen_probe_div: PerHeld = jax.vmap(
lambda point, key: divergence(trained_field, point, 0.5, 16, key)
)(held_points, row_keys)print(
f"exact divergence across rows: mean {float(exact_div.mean()):.3f}, spread {float(exact_div.std()):.3f}"
)
for name, estimate_div in [
("1 probe", one_probe_div),
("16 probes", sixteen_probe_div),
]:
# the error of the estimate at each row, (held_out)
div_error: PerHeld = estimate_div - exact_div
print(
f"{name:>9s}: mean error {float(div_error.mean()):+.3f}, RMSE {float(jnp.sqrt(jnp.mean(div_error**2))):.3f}"
)exact divergence across rows: mean -2.525, spread 1.556
1 probe: mean error +0.170, RMSE 2.529
16 probes: mean error -0.067, RMSE 0.598
fig, axes = plt.subplots(1, 2, figsize=(11, 4.6), sharex=True, sharey=True)
for ax, (name, estimate_div) in zip(
axes, [("1 probe", one_probe_div), ("16 probes", sixteen_probe_div)], strict=True
):
ax.scatter(
np.asarray(exact_div), np.asarray(estimate_div), color=DATA_COLOR, **SCATTER_KW
)
span = [float(exact_div.min()), float(exact_div.max())]
ax.plot(span, span, "k--", lw=1)
ax.set(title=name, xlabel="exact $\\mathrm{tr}(J_v)$")
style_ax(ax)
axes[0].set_ylabel("Hutchinson estimate")
plt.show()
Figure 2:The divergence of the trained 6-D vector field at t = 0.5 at each held-out row: the estimate with one probe (left) and with 16 probes (right) against the exact trace, with the identity line dashed.
Across rows the exact divergence has mean −2.53 and spread 1.56. One probe estimates it with an RMSE of 2.53, more than that spread, so a single probe at a single step barely tells the rows apart; 16 probes bring the RMSE down to 0.60, about four times smaller, as predicts. The mean errors, +0.17 and −0.07, are small next to the RMSEs.
4. The error in the log-density¶
The solver integrates the estimate over the path, so the log-density inherits an error that is a sum of the per-step errors. A FFJORD draws its probes once, from its trace_key, and uses them at every step and for every point. We build FFJORDs with the trained vector field and 1 to 32 probes, each with six different keys, and compare their log-densities on 100 held-out rows with the exact one.
# Shapes: test = the first 100 held-out rows
# the rows we test on, (test, state)
test_rows: Float[ArrayLike, "test state"] = held_points[:100]# Shapes: probe_count = 6 probe counts; seed = 6 keys
PerTest = Float[ArrayLike, " test"]
# user
# the exact log-density of each check row, (test)
exact_logp: PerTest = log_density(trained_field, test_rows)
# the probe counts N_p
logp_counts: list = [1, 2, 4, 8, 16, 32]
# user
# the error log p̂ − log p of every count, key and row, (probe_count, seed, test)
logp_errors: Float[ArrayLike, "probe_count seed test"] = np.array(
[
[
log_density(trained_field, test_rows, "hutchinson", count, seed)
- exact_logp
for seed in range(6)
]
for count in logp_counts
]
)# the mean error over keys and rows, the bias, (probe_count)
logp_bias: Float[ArrayLike, " probe_count"] = logp_errors.mean(axis=(1, 2))
# the RMSE over keys and rows, (probe_count)
logp_rmse: Float[ArrayLike, " probe_count"] = np.sqrt(
(logp_errors**2).mean(axis=(1, 2))
)
# the error in the mean log-density of the 100 rows, one per key, (probe_count, seed)
batch_error: Float[ArrayLike, "probe_count seed"] = logp_errors.mean(axis=2)
for count, bias, rmse, batch in zip(
logp_counts, logp_bias, logp_rmse, batch_error, strict=True
):
print(
f"N_p = {count:2d}: bias {bias:+.4f}, RMSE per row {rmse:.4f}, largest error of a batch mean {np.abs(batch).max():.4f}"
)N_p = 1: bias +0.1291, RMSE per row 2.2715, largest error of a batch mean 0.7493
N_p = 2: bias +0.0267, RMSE per row 1.5170, largest error of a batch mean 0.4829
N_p = 4: bias -0.0139, RMSE per row 1.0861, largest error of a batch mean 0.2745
N_p = 8: bias -0.0001, RMSE per row 0.8928, largest error of a batch mean 0.1763
N_p = 16: bias -0.0206, RMSE per row 0.5672, largest error of a batch mean 0.1788
N_p = 32: bias +0.0020, RMSE per row 0.4649, largest error of a batch mean 0.0953
fig, ax = plt.subplots(figsize=(7, 4.2))
ax.loglog(logp_counts, logp_rmse, "o-", color=DATA_COLOR, label="RMSE per row")
ax.loglog(logp_counts, np.abs(logp_bias), "s--", color=LATENT_COLOR, label="|bias|")
ax.loglog(
logp_counts, logp_rmse[0] / np.sqrt(logp_counts), "k:", label="$1/\\sqrt{N_p}$"
)
ax.set(xlabel="probes $N_p$", ylabel="error in $\\log p_x$ (nats)")
ax.legend()
style_ax(ax)
plt.show()
Figure 3:The error that the Hutchinson trace leaves in the log-density of 100 held-out rows of the 6-D toy, over six probe keys: the root-mean-square error per row (circles), the absolute bias (squares), and a line falling as one over the square root of the number of probes (dotted).
The RMSE per row falls from 2.27 nats at one probe to 0.46 at 32, close to , and the bias stays between −0.02 and +0.13 nats with no trend. Averaging over rows helps less than it seems: at one probe the error of the mean log-density of 100 rows reaches 0.75 nats, while 100 independent errors with an RMSE of 2.27 would leave about 0.23. All the rows share the FFJORD’s probes, so their errors are correlated. A per-row log-density, for anomaly scores for example, needs many probes or the exact trace, and so does a precise mean.
5. Fixed probes¶
Because a FFJORD draws its probes once, its log-density is a deterministic function of its weights: calling the same FFJORD twice gives the same numbers, and the optimiser sees one objective rather than a new random one at every step. Only a FFJORD with another trace_key gives other numbers.
# user
# the log-density with one probe from jr.key(0), (test)
first_call: PerTest = log_density(trained_field, test_rows, "hutchinson", 1, 0)
# user
# the same, computed again, (test)
second_call: PerTest = log_density(trained_field, test_rows, "hutchinson", 1, 0)
# user
# the log-density with one probe from jr.key(1), (test)
other_key: PerTest = log_density(trained_field, test_rows, "hutchinson", 1, 1)
print(
f"same key, two calls : largest difference {float(jnp.abs(first_call - second_call).max()):.1e}"
)
print(
f"another key : largest difference {float(jnp.abs(first_call - other_key).max()):.3f}"
)same key, two calls : largest difference 0.0e+00
another key : largest difference 6.373
Fixed probes have a side effect that is easiest to see in two dimensions. A Rademacher probe in 2-D has , so its estimate is the trace plus one cross term:
With fixed probes the error of every step is , where is one number fixed by the key, and the error of the log-density is times the integral of along the path. More probes do not shrink the error smoothly; they change , which can take the same value for two counts. We read off the keys that the FFJORD example uses for its probe sweep, as the Hutchinson estimate of the trace of , which is exactly .
# today (lineax)
# the matrix with a single one above the diagonal, whose εᵀ E ε is ε₁ ε₂
cross_op: lx.MatrixLinearOperator = lx.MatrixLinearOperator(
jnp.array([[0.0, 1.0], [0.0, 0.0]])
)for count in [1, 4, 16, 64, 256]:
# today (gauss_flows)
# the probe key of the example's FFJORD with N_p probes
example_key: Key[jax.Array, ""] = FFJORD(
jr.key(12345 + count), shape=(2,)
).trace_key
# today (gaussx)
# ε̄₁₂ = (1/N_p) ∑ᵢ εᵢ₁ εᵢ₂, with the FFJORD's probes
cross_mean: float = float(
gaussx.trace(
cross_op,
stochastic=True,
num_probes=count,
key=example_key,
algorithm="hutchinson",
)
)
print(f"N_p = {count:3d}: mean of eps_1 eps_2 = {cross_mean:+.4f}")N_p = 1: mean of eps_1 eps_2 = -1.0000
N_p = 4: mean of eps_1 eps_2 = -0.5000
N_p = 16: mean of eps_1 eps_2 = -0.1250
N_p = 64: mean of eps_1 eps_2 = -0.1250
N_p = 256: mean of eps_1 eps_2 = -0.1094
These are the ratios in the example’s table: its RMSE at 4, 16, 64 and 256 probes (0.9317, 0.2329, 0.2329 and 0.2038) is 1/2, 1/8, 1/8 and 7/64 of its RMSE at one probe (1.8635), the values of here. In 2-D the error at every point is times an integral that does not depend on the probes, so the RMSE over points is times a fixed number, and more probes help only through . In 2-D the exact trace costs two products, which is why notebook 00 uses it throughout.
6. Training on fixed probes¶
Fixed probes make the objective deterministic, but they also make it a different objective: the training loss is the log-density under the estimate with those probes, not under the trace. The estimate is unbiased over random probes, not for one fixed set, and an optimiser that always sees the same probes can lower the loss by moving along those probes without moving the trace. We train the same fresh vector field as in section 3 with FFJORD’s default, one fixed Rademacher probe, and evaluate it three ways.
# today (gauss_flows)
# the ODE flow with FFJORD's default trace, one fixed Rademacher probe, solved to 10⁻⁴
probe_ffjord: FFJORD = FFJORD(
jr.key(6), shape=(6,), vector_field=vector_field, rtol=1e-4, atol=1e-4
)
# user
# v_θ̂ trained on one fixed probe, and the training time
probe_field: DiffeqMLP
probe_seconds: float
probe_field, probe_seconds = train_field(probe_ffjord)
# the probe key the flow trained with
train_seed: int = 6# user
# the held-out NLL with the training probes
nll_training_probes: float = -float(
log_density(probe_field, held_points, "hutchinson", 1, train_seed).mean()
)
# user
# the held-out NLL with the exact trace
nll_exact: float = -float(log_density(probe_field, held_points).mean())
# user
# the held-out NLL with the probes of two other keys
nll_other: list = [
-float(log_density(probe_field, held_points, "hutchinson", 1, seed).mean())
for seed in (7, 8)
]
print(f"training took {probe_seconds / 60:.1f} min")
print(f"held-out NLL with the training probes: {nll_training_probes:.1f}")
print(
f"held-out NLL with the exact trace : {nll_exact:.1f} (exact training: {held_nll:.3f}, untrained: {initial_nll:.3f})"
)
print(f"held-out NLL with two other probe keys: {nll_other[0]:.1f}, {nll_other[1]:.1f}")training took 1.3 min
held-out NLL with the training probes: -8172.5
held-out NLL with the exact trace : 117.9 (exact training: 6.921, untrained: 8.552)
held-out NLL with two other probe keys: 1280.0, -150.5
The training loss, the NLL with the training probes, ends at −8172.5 nats on the held-out rows, a value no density on these data could reach. The exact NLL of the same flow is 117.9, worse than the untrained flow’s 8.55 and far from the 6.92 of exact training, and the probes of two other keys give 1280.0 and −150.5. The optimiser has fitted the probes, not the data. This is a bug in gauss_flows (gauss_flows#267): FFJORD keeps its probes for the whole of training, so the estimate is unbiased over keys but not along one run, and the issue measures the fix of drawing fresh probes at every step. Until it is fixed, train with divergence_mode="exact", as section 3 does.
7. The cost¶
The exact trace materialises with forward-mode products; one probe needs one. We time one divergence evaluation of a fresh DiffeqMLP of the same size as before, compiled once, for from 2 to 512.
# Shapes: size = 5 dimensions
# user
# seconds per compiled divergence evaluation of a fresh field on R^size
def time_divergence(size: int, num_probes: int) -> float:
"""Mean wall time of one divergence evaluation, over 50 calls after compiling."""
# today (gauss_flows)
# a fresh field v(t, x) on R^size
field: DiffeqMLP = DiffeqMLP(
jr.key(size), in_dim=size, control_dim=0, hidden=(64, 64)
)
# today (jax)
# the divergence at one point, exact or with one probe, compiled
compiled: Callable = jax.jit(
lambda x: divergence(field, x, 0.5, num_probes, jr.key(0))
)
# x ~ N(0, I), (state)
point: Float[ArrayLike, " state"] = jr.normal(jr.key(size + 1), (size,))
compiled(point).block_until_ready()
# the clock after compiling
start: float = time.perf_counter()
for _ in range(50):
compiled(point).block_until_ready()
return (time.perf_counter() - start) / 50# the dimensions D_x
sizes: list = [2, 8, 32, 128, 512]
# user
# milliseconds per evaluation with the exact trace, (size)
exact_ms: Float[ArrayLike, " size"] = 1e3 * np.array(
[time_divergence(size, 0) for size in sizes]
)
# user
# milliseconds per evaluation with one probe, (size)
probe_ms: Float[ArrayLike, " size"] = 1e3 * np.array(
[time_divergence(size, 1) for size in sizes]
)
for size, exact_time, probe_time in zip(sizes, exact_ms, probe_ms, strict=True):
print(f"D_x = {size:3d}: exact {exact_time:.3f} ms, one probe {probe_time:.3f} ms")D_x = 2: exact 0.053 ms, one probe 0.050 ms
D_x = 8: exact 0.076 ms, one probe 0.045 ms
D_x = 32: exact 0.090 ms, one probe 0.048 ms
D_x = 128: exact 0.107 ms, one probe 0.079 ms
D_x = 512: exact 1.018 ms, one probe 0.072 ms
fig, ax = plt.subplots(figsize=(7, 4.2))
ax.loglog(sizes, exact_ms, "o-", color=DATA_COLOR, label="exact trace, $D_x$ products")
ax.loglog(sizes, probe_ms, "s-", color=LATENT_COLOR, label="one probe, one product")
ax.set(xlabel="dimension $D_x$", ylabel="ms per evaluation")
ax.legend()
style_ax(ax)
plt.show()
Figure 4:Wall time of one compiled divergence evaluation of an MLP vector field with two hidden layers of 64 units, against the dimension: the exact trace (D_x Jacobian-vector products) and Hutchinson’s estimate with one probe (one product).
At both take about 0.05 ms, because a compiled call this small is dominated by overhead, not by products. The exact trace then grows, slowly while its products run as one batched call and then steeply, to 1.02 ms at , while one probe stays below 0.08 ms, so at the exact trace costs about 14 times as much. These are wall times on a shared machine and move by a few hundredths of a millisecond between runs; the growth at 512 does not. Every solver step pays this cost, and training pays it again in the backward pass.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| the trace as an expectation | (1) | |
| Hutchinson’s estimate from probes | (2) | gaussx.trace(op, stochastic=True, num_probes=N_p, algorithm="hutchinson") |
| Rademacher and Gaussian variances | (3) | sampler="signs" or "normal"; FFJORD(..., probe_distribution=...) |
| the divergence of a vector field | (3) | gaussx.trace of lx.JacobianLinearOperator(field, x, jac="fwd") |
| the estimate inside a flow | (4) | FFJORD(..., divergence_mode="hutchinson", n_hutchinson_samples=N_p) |
| probes fixed per flow | (4) | FFJORD.trace_key |
| training on one fixed probe | fits the probes, not the data (gauss_flows#267); train with divergence_mode="exact" until it is fixed | |
| sketch-based estimators | algorithm="hutchpp" or "xtrace" in gaussx, not offered by FFJORD |
Next. Not every continuous flow needs an estimate of the trace. Notebook 02 takes a linear vector field, whose flow is a matrix exponential and whose log-determinant is exact and in closed form.
- Hutchinson, M. F. (1990). A stochastic estimator of the trace of the influence matrix for Laplacian smoothing splines. Communications in Statistics — Simulation and Computation, 19(2), 433–450.
- Grathwohl, W., Chen, R. T. Q., Bettencourt, J., Sutskever, I., & Duvenaud, D. (2019). FFJORD: Free-Form Continuous Dynamics for Scalable Reversible Generative Models. International Conference on Learning Representations (ICLR).