BUG: ADVI default optimizer adagrad_window biases posterior SDs upward (~8.5% on a conjugate Gaussian): the current gradient is inside its own normaliser
Describe the issue:
Summary
arXiv 2608.01403 (Andersen, Bersson, Broderick) reports that default ADVI settles with posterior SDs above the exact value on a conjugate 1-D Gaussian model, and stays there for millions of iterations. The defaults are MeanField, 1 MC gradient sample, adagrad_window. The posterior mean is fine, and obj_n_mc=100 or adam removes the bias. The authors say the issue "has not been previously documented" and give no mechanism.
Cause: adagrad_window divides each gradient by a window of squared gradients that includes that same gradient (updates.py, accu_sum = accu_new.sum(axis=-1), line 583 in 6.3.2). With one MC sample, the gradient for the scale parameter rho is unbiased but right-skewed (χ²-shaped). A step of g / sqrt(g² + S) damps large |g| more than small |g|, so it behaves like a soft median. The iterate settles where E[g/sqrt(g² + S)] = 0, not where E[g] = 0. That shifts σ upward.
The noise on the mean parameter is symmetric, so the mean is unaffected. This matches the paper.
Evidence
Model: mu ~ N(0,1), y_i ~ N(mu,1), n = 10. The exact posterior SD is 1/√11. The metric is softplus(rho) averaged over the second half of each run.
| setting | PyMC 5.25.1, 300k iterations, 3 seeds | first-principles prediction* (two independent numpy solvers) |
|---|---|---|
default (n_win=10) |
+8.5 % (6.3.2, 400k × 3 seeds: +8.6 %) | +8.7 – 8.8 % |
stock rule, n_win = 1 / 2 / 5 / 20 |
+41.3 / +28.7 / +15.1 / +4.5 % | +41.2–41.4 / +28.4–28.9 / +15.2 / +4.7–4.9 % |
current gradient excluded, n_win=1 (control: plain scaled SGD) |
−0.2 % | 0 % |
current gradient excluded, n_win=10 |
−0.2 % | ~0 % |
*A pure-numpy fixed point of E[step] = 0, with the mean held at its optimum; no PyMC involved. The ELBO gradient w.r.t. ρ is sigmoid(ρ)·(1/σ − (1+n)·σ·ε²), with ε ~ N(0,1). The optimiser minimises −ELBO, whose gradient is the sign-flip of that: right-skewed, χ²-shaped.
The paper's own fixes, in separate runs on the same model: obj_n_mc=100 gave +0.05 % (200k × 2 seeds) and adam gave +0.1 % (400k × 4 seeds).
- Consistent with the mechanism: the n_win = 1 case, where the stock step is ≈ lr·sign(g) and so settles at the median of the gradient noise, is predicted at +41 % and measured at +41 %.
- Robust: in the fixed-point calculation, the bias is nearly independent of n (0 to 1000). It shrinks only for very wide posteriors, where
epsilon=0.1dominates the normaliser (posterior SD 10 → about +5 %). This is only a guess at why the paper reports "about 5 %"; its exact prior and likelihood scales were not checked here. - Another model: a heavy-tailed check (Student-t likelihood with 3 outliers; 100k × 3 seeds) shows the same direction: default SD 0.26 vs 0.24 with the current gradient excluded.
Suggested fix
Normalise by the other n_win − 1 squared gradients. Keep a hard step bound, because the stock rule guarantees |Δθ| < lr and excluding the current gradient removes that guarantee. Use the stock rule until the window has filled.
# in adagrad_window, per parameter (t = new shared step counter, max_step_ratio=10 new kwarg)
accu_sum = accu_new.sum(axis=-1)
stock_step = learning_rate * grad / pt.sqrt(accu_sum + epsilon)
excl_step = learning_rate * grad / pt.sqrt(pt.maximum(accu_sum - grad**2, 0) + epsilon) # current gradient excluded
excl_step = pt.clip(excl_step, -max_step_ratio * learning_rate, max_step_ratio * learning_rate)
updates[t] = t + 1
updates[param] = param - pt.switch(t < n_win, stock_step, excl_step)- Bias with the fix: −0.2 % (as above). With
n_win=1the fixed rule is constant-scale SGD (lr·g/√epsilon), which is why it is the right control. - Size of the cap: a cap of 1·lr brings the bias back (+5.4 % measured, +5.6 % predicted), because it clips exactly the tail that matters. 10·lr never engaged in these tests: the largest step was 2.6·lr on the Student-t model. It is a safety net, not something these models needed.
- Alternatives:
- making
adamthe default removes the bias too, but changes the behaviour of the mean as well; - a larger
n_winonly dilutes the bias (still +4.5 % atn_win=20) and adapts more slowly; - raising
obj_n_mcmultiplies the cost.
- making
User-visible effect of any fix: MeanField SDs from default ADVI get ~8 % smaller. MeanField tends to under-estimate posterior spread on correlated models, so the current bias can partly mask that.
A possible regression test: in the model above, the SD should be within 2 % of 1/√11 after 200k iterations, with 1 MC sample, averaged over ≥ 3 seeds.
Workarounds today: obj_optimizer=pm.adam(), obj_n_mc=100, or the function in the code example below.
Reproduceable code example:
import numpy as np
import pymc as pm
import pytensor
import pytensor.tensor as pt
from collections import OrderedDict
from pymc.variational.updates import get_or_compute_grads
def adagrad_window_fixed(learning_rate=0.001, epsilon=0.1, n_win=10, max_step_ratio=10.0):
"""adagrad_window, but each step is normalised by the OTHER n_win-1 squared gradients (current excluded),
with |step| <= max_step_ratio * learning_rate, and the stock rule while the window is filling."""
def opt(loss_or_grads, params):
grads = get_or_compute_grads(loss_or_grads, params)
updates = OrderedDict()
for param, grad in zip(params, grads):
i = pytensor.shared(pm.pytensorf.floatX(0)); t = pytensor.shared(pm.pytensorf.floatX(0))
value = param.get_value(borrow=True)
accu = pytensor.shared(np.zeros((*value.shape, n_win), dtype=value.dtype))
accu_new = pt.set_subtensor(accu[..., i.astype("int32")], grad**2)
updates[accu] = accu_new
updates[i] = pt.switch((i + 1) < n_win, i + 1, 0)
updates[t] = t + 1
accu_sum = accu_new.sum(axis=-1)
stock_step = learning_rate * grad / pt.sqrt(accu_sum + epsilon)
excl_step = learning_rate * grad / pt.sqrt(accu_sum - grad**2 + epsilon)
excl_step = pt.clip(excl_step, -max_step_ratio * learning_rate, max_step_ratio * learning_rate)
updates[param] = param - pt.switch(t < n_win, stock_step, excl_step)
return updates
return opt
y = np.random.default_rng(0).normal(0.5, 1.0, size=10)
exact_sd = 1 / np.sqrt(1 + len(y)) # mu ~ N(0,1), y_i ~ N(mu,1): posterior SD = 1/sqrt(n+1)
def fitted_sd(optimizer, seed, n=200_000):
with pm.Model():
mu = pm.Normal("mu", 0, 1)
pm.Normal("y", mu, 1, observed=y)
advi = pm.ADVI(random_seed=seed)
rho = {p.name: p for p in advi.approx.params}["rho"]
sds = []
cb = lambda approx, loss, i: sds.append(np.log1p(np.exp(rho.get_value()[0]))) if i > n // 2 and i % 10 == 0 else None
advi.fit(n=n, obj_optimizer=optimizer, callbacks=[cb], progressbar=False)
return np.mean(sds) # average over the second half of the run
for name, make in [("default adagrad_window", pm.adagrad_window), ("adagrad_window, current excluded", adagrad_window_fixed)]:
bias = [100 * (fitted_sd(make(), seed) / exact_sd - 1) for seed in (1, 2)]
print(f"{name:34s} SD bias: {np.mean(bias):+.2f}% (seeds: {', '.join(f'{b:+.2f}' for b in bias)})")Error message:
No error: the problem is a biased result. Output on PyMC 6.3.2:
default adagrad_window SD bias: +8.88% (seeds: +8.54, +9.23)
adagrad_window, current excluded SD bias: +0.26% (seeds: -0.10, +0.61)PyMC version information:
PyMC 6.3.2 (latest; also reproduced on 5.25.1, the version used in the paper) PyTensor 3.3.2 (with 5.25.1: 2.31.7) Python 3.12.3 Operating system: Ubuntu 24.04 (WSL2) Installed via pip
Context for the issue:
Default ADVI is what most users run, and MeanField scale parameters fit with 1 MC sample are exposed to this optimiser bias (its size depends on the model and its scale; ~8.5 % in the model above). The fix above removes it at negligible cost, and the regression test would keep it fixed.
The mechanism and fix were cross-checked by an independent review, which proposed the n_win = 1 prediction test and the step-bound concern. This is a one-off report: the reporter can't follow up, so everything needed to verify it is above.
Source: pymc-devs/pymc