Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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

Open In Colab

The log-density of a continuous flow (4) integrates the trace of the vector field’s Jacobian Jv\mat{J}_v 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.

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 ϵ∈RDx\gvect{\epsilon} \in \mathbb{R}^{D_x} be a random probe with zero mean and identity covariance, E[ϵϵ⊤]=I\mathbb{E}[\gvect{\epsilon} \gvect{\epsilon}^\top] = \mat{I}. For any square matrix A\mat{A}, E[ϵ⊤Aϵ]=∑i,jAijE[ϵiϵj]=∑iAii\mathbb{E}[\gvect{\epsilon}^\top \mat{A} \gvect{\epsilon}] = \sum_{i, j} A_{ij} \mathbb{E}[\epsilon_i \epsilon_j] = \sum_i A_{ii}, so

tr(A)=Eϵ[ϵ⊤Aϵ]\mathrm{tr}(\mat{A}) = \mathbb{E}_{\gvect{\epsilon}}[\gvect{\epsilon}^\top \mat{A} \gvect{\epsilon}]

and the average over NpN_p independent probes is an unbiased estimate of the trace:

tr^(A)=1Np∑i=1Npϵi⊤Aϵi\widehat{\mathrm{tr}}(\mat{A}) = \frac{1}{N_p} \sum_{i=1}^{N_p} \gvect{\epsilon}_i^\top \mat{A} \gvect{\epsilon}_i

The estimate never needs A\mat{A} itself, only the products Aϵi\mat{A} \gvect{\epsilon}_i. For the Jacobian of a vector field, Jvϵ\mat{J}_v \gvect{\epsilon} is one forward-mode Jacobian-vector product, so NpN_p probes cost NpN_p products against the DxD_x of the exact trace. Two probe distributions are common: Rademacher probes, whose entries are ±1\pm 1 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 A∈RDx×Dx\mat{A} \in \mathbb{R}^{D_x \times D_x} with Dx=24D_x = 24, wrapped as a lineax operator so that gaussx sees only its matrix-vector products.

We draw 4000 estimates with a single Rademacher probe each.

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, −2.03±0.36-2.03 \pm 0.36, is within one standard error of tr(A)=−1.78\mathrm{tr}(\mat{A}) = -1.78: 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 NpN_p probes divides the variance by NpN_p, so the root-mean-square error should fall as 1/Np1/\sqrt{N_p}. We measure it over 400 repeats for NpN_p from 1 to 256.

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]
<Figure size 1200x420 with 2 Axes>

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 1/Np1/\sqrt{N_p}, 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 A\mat{A} the variance of one probe’s estimate has a closed form for each distribution:

VarRademacher[ϵ⊤Aϵ]=2(∥A∥F2−∑d=1DxAdd2),VarGauss[ϵ⊤Aϵ]=2∥A∥F2\begin{aligned} \mathrm{Var}_{\mathrm{Rademacher}}[\gvect{\epsilon}^\top \mat{A} \gvect{\epsilon}] &= 2 \left( \Vert \mat{A} \Vert_F^2 - \sum_{d=1}^{D_x} A_{dd}^2 \right), \\ \mathrm{Var}_{\mathrm{Gauss}}[\gvect{\epsilon}^\top \mat{A} \gvect{\epsilon}] &= 2 \Vert \mat{A} \Vert_F^2 \end{aligned}

A Rademacher probe has ϵd2=1\epsilon_d^2 = 1 exactly, so the diagonal of A\mat{A} enters every estimate with weight one and contributes no variance; only the off-diagonal entries do. A Gaussian probe has ϵd2\epsilon_d^2 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.

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 ∥A∥F2\Vert \mat{A} \Vert_F^2, 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 A\mat{A} 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 A\mat{A} decays. We compare the three at the same number of matrix-vector products.

 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 DxD_x 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 R24\mathbb{R}^{24} 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 u\vect{u}, bent coordinate by coordinate to u+0.6sin⁡(2u)\vect{u} + 0.6 \sin(2 \vect{u}) and mixed by a random rotation, then standardised. There are Nt=1200N_t = 1200 training rows and Nv=300N_v = 300 held-out rows.

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 5×10−35 \times 10^{-3}, the gradient clipped to a global norm of 1, 300 steps of 256 rows.

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 Jv(t,x)\mat{J}_v(t, \vect{x}). We compute it at t=0.5t = 0.5 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.

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.

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
<Figure size 1100x460 with 2 Axes>

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 1/161/\sqrt{16} 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.

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
<Figure size 700x420 with 1 Axes>

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 1/Np1/\sqrt{N_p}, 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.

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 ϵ12=ϵ22=1\epsilon_1^2 = \epsilon_2^2 = 1, so its estimate is the trace plus one cross term:

ϵ⊤Jvϵ=tr(Jv)+ϵ1ϵ2(J12+J21)\gvect{\epsilon}^\top \mat{J}_v \gvect{\epsilon} = \mathrm{tr}(\mat{J}_v) + \epsilon_1 \epsilon_2 (J_{12} + J_{21})

With NpN_p fixed probes the error of every step is ϵˉ12(J12+J21)\bar{\epsilon}_{12} (J_{12} + J_{21}), where ϵˉ12=1Np∑iϵi,1ϵi,2\bar{\epsilon}_{12} = \frac{1}{N_p} \sum_i \epsilon_{i,1} \epsilon_{i,2} is one number fixed by the key, and the error of the log-density is ϵˉ12\bar{\epsilon}_{12} times the integral of J12+J21J_{12} + J_{21} along the path. More probes do not shrink the error smoothly; they change ϵˉ12\bar{\epsilon}_{12}, which can take the same value for two counts. We read ϵˉ12\bar{\epsilon}_{12} off the keys that the FFJORD example uses for its probe sweep, as the Hutchinson estimate of the trace of (0100)\left(\begin{smallmatrix} 0 & 1 \\ 0 & 0 \end{smallmatrix}\right), which is exactly ϵˉ12\bar{\epsilon}_{12}.

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 ∣ϵˉ12∣\vert \bar{\epsilon}_{12} \vert here. In 2-D the error at every point is ϵˉ12\bar{\epsilon}_{12} times an integral that does not depend on the probes, so the RMSE over points is ∣ϵˉ12∣\vert \bar{\epsilon}_{12} \vert times a fixed number, and more probes help only through ϵˉ12\bar{\epsilon}_{12}. 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 ϵ⊤Jvϵ\gvect{\epsilon}^\top \mat{J}_v \gvect{\epsilon} 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.

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 Jv\mat{J}_v with DxD_x 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 DxD_x from 2 to 512.

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
<Figure size 700x420 with 1 Axes>

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 Dx=2D_x = 2 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 DxD_x products run as one batched call and then steeply, to 1.02 ms at Dx=512D_x = 512, while one probe stays below 0.08 ms, so at Dx=512D_x = 512 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

PieceEquationIn code
the trace as an expectation(1)
Hutchinson’s estimate from NpN_p 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 probefits the probes, not the data (gauss_flows#267); train with divergence_mode="exact" until it is fixed
sketch-based estimatorsalgorithm="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.

References
  1. 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.
  2. 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).