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.

Wet and dry days: a non-Gaussian likelihood with the path integrated out or sampled

Open In Colab

In Examples 1, 2 and 3 the observations were Gaussian, so the Kalman filter integrated the latent path out exactly and NUTS only saw the hyperparameters. In Example 3b the observations were counts, and NUTS had to sample every latent value. Here we take one station’s record of wet and dry days, a Bernoulli observation of a latent log odds, and fit it both ways. Route A integrates the path out approximately with a Laplace approximation, so NUTS again samples only the hyperparameters. Route B samples the path through whitened innovations, as Example 3b did, so its posterior is exact up to the Monte Carlo error of the chains. Since we simulate the record, we know the truth, and Route B gives us the reference to check Route A against: its hyperparameters, its latent wet-day probability through the gaps and the forecast, and what it costs.

pyrox-ssm capability shown: markov_laplace_factor, which fits the latent path with a site-based strategy (LaplaceMarkovInference here, ExpectationPropagationMarkov for comparison) and adds its approximate log evidence as a NumPyro factor, with reject_unconverged=True so NUTS rejects any θ\boldsymbol{\theta} whose fit did not converge; MarkovGPPrior.condition_nongauss(...).predict(...), the conditioned non-Gaussian posterior at arbitrary days; and markov_gp_innovations_sample for Route B. The strategies iterate to a fixed point with optimistix.fixed_point, and their gradient comes from the implicit function theorem at that fixed point, so the factor jits and differentiates inside NUTS. Cost: every Route A log-density evaluation is a few Kalman filter and smoother passes, O(INDx3)\mathcal{O}(I N D_x^3) for II fixed-point iterations, plus the implicit gradient; every Route B evaluation is one scan, O(TDx3)\mathcal{O}(T D_x^3), but NUTS has to move TDxT D_x more values. We measure both, per gradient, per draw and per effective sample, in section 8.

What you’ll learn:

  1. How to write a Bernoulli model on a Markov GP as a plain NumPyro function in two ways: with the path collapsed by markov_laplace_factor, and with the path sampled by markov_gp_innovations_sample.

  2. How the hyperparameter posteriors of the two routes compare with each other and with the truth.

  3. How to predict the latent wet-day probability through withheld days and a forecast from Route A’s conditioned posterior, averaged over its NUTS draws, and how it compares with Route B’s.

  4. Where the Laplace approximation is close to the exact posterior and where it is biased, and what each route costs.

The Matérn-3/2 SDE and the Kalman filter are explained in Example 1, and the whitened innovations in Example 3b. For the four site-based strategies (Laplace, Gauss-Newton, posterior linearisation and EP) at fixed hyperparameters, see Non-Gaussian Markov GP inference. We reuse all three here without deriving them again.

Why pyrox_gp and pyrox_ssm appear together

The Bernoulli observation model is pyrox_gp.BernoulliLikelihood. pyrox_ssm never imports pyrox_gp (its import-guard test forbids it, see AGENTS.md), and its strategies take any pyrox.likelihoods.Likelihood, the protocol that lives in the shared pyrox core. So, as in Example 3b, we import both and compose them in one model: the packages do not depend on each other, the user does.

Background

The days tkt_k, k=1,…,Tk = 1, \ldots, T, form the grid Tx\mathcal{T}_x of T≡NTxT \equiv N_{\mathcal{T}_x} days, counted from 1 January. The first NN of them are the record and the last T−NT - N are a forecast. On day tkt_k the station reports yk∈{0,1}y_k \in \{0, 1\}, 1 for a wet day, when the mask ok∈{0,1}o_k \in \{0, 1\} is 1, and ok=0o_k = 0 on the forecast days and on the days the station missed. The wet-day probability pk∈(0,1)p_k \in (0, 1) is the logistic function σ(⋅)\sigma(\cdot) of a seasonal mean of the log odds plus a Matérn-3/2 anomaly,

yk∼Bernoulli(pk)y_k \sim \mathrm{Bernoulli}(p_k)
log⁡pk1−pk=μ(tk)+f(tk)\log \frac{p_k}{1 - p_k} = \mu(t_k) + f(t_k)
μ(t)=c+acos⁡(ωt)+bsin⁡(ωt)\mu(t) = c + a \cos(\omega t) + b \sin(\omega t)
f∼GP(0,kMateˊrn-3/2(t,t′;σf2,ℓ))f \sim \mathcal{GP}(0, k_\text{Matérn-3/2}(t, t'; \sigma_f^2, \ell))

where ω=2π/365.25 days−1\omega = 2\pi / 365.25 \text{ days}^{-1} as in Example 1, a,b∈Ra, b \in \mathbb{R} set the shape of the seasonal cycle of the log odds, c∈Rc \in \mathbb{R} is the station’s offset from it, and the anomaly ff (in log-odds units) has the kernel variance σf2∈R>0\sigma_f^2 \in \mathbb{R}_{>0} and the lengthscale ℓ∈R>0\ell \in \mathbb{R}_{>0} (days). A record of a few months cannot pin down an annual cycle, so we take aa and bb as known, from the station’s long-term climatology, and infer θ=(c,σf2,ℓ)∈R3\boldsymbol{\theta} = (c, \sigma_f^2, \ell) \in \mathbb{R}^{3}. With f=μ(t1:N)+f(t1:N)∈RN\mathbf{f} = \mu(t_{1:N}) + f(t_{1:N}) \in \mathbb{R}^{N} the log odds on the record days, the log likelihood keeps only the observed days,

log⁡p(y∣f)=∑k=1Nok(yklog⁡pk+(1−yk)log⁡(1−pk))\log p(\mathbf{y} \mid \mathbf{f}) = \sum_{k=1}^{N} o_k (y_k \log p_k + (1 - y_k) \log(1 - p_k))

with y∈{0,1}N\mathbf{y} \in \{0, 1\}^{N} the record. There is no Kalman marginal for it, so the two routes deal with f\mathbf{f} differently.

Route A, collapsed. We integrate f\mathbf{f} out with a Laplace approximation and give NUTS the three values of θ\boldsymbol{\theta} only. With f^∈RN\hat{\mathbf{f}} \in \mathbb{R}^{N} the mode of p(f∣y,θ)p(\mathbf{f} \mid \mathbf{y}, \boldsymbol{\theta}), p^k=σ(f^k)\hat{p}_k = \sigma(\hat{f}_k) and Ktt∈RN×N\mathbf{K}_{tt} \in \mathbb{R}^{N \times N} the Matérn-3/2 kernel matrix over the record days, the approximate log evidence is

log⁡p(y∣θ)≈log⁡p(y∣f^)+log⁡N(f^;μ,Ktt)−12log⁡det⁡(IN+ΛsiteKtt)\log p(\mathbf{y} \mid \boldsymbol{\theta}) \approx \log p(\mathbf{y} \mid \hat{\mathbf{f}}) + \log \mathcal{N}(\hat{\mathbf{f}}; \boldsymbol{\mu}, \mathbf{K}_{tt}) - \frac{1}{2} \log \det(\mathbf{I}_N + \boldsymbol{\Lambda}_\text{site} \mathbf{K}_{tt})

where μ=μ(t1:N)∈RN\boldsymbol{\mu} = \mu(t_{1:N}) \in \mathbb{R}^{N} and Λsite=diag(okp^k(1−p^k))∈RN×N\boldsymbol{\Lambda}_\text{site} = \mathrm{diag}(o_k \hat{p}_k (1 - \hat{p}_k)) \in \mathbb{R}^{N \times N} holds the curvature of the log likelihood at the mode, zero on a missed day. pyrox-ssm never forms Ktt\mathbf{K}_{tt}. It replaces each observed day by a Gaussian site, a pseudo-observation of f(tk)f(t_k) with precision Λsite,k=p^k(1−p^k)\Lambda_{\text{site},k} = \hat{p}_k (1 - \hat{p}_k), and gets f^\hat{\mathbf{f}} and all three terms from Kalman filter and RTS smoother passes over the sites. Finding f^\hat{\mathbf{f}} is a Newton iteration on the site natural parameters s∈R2N\mathbf{s} \in \mathbb{R}^{2N}, a fixed point s⋆=T(s⋆;θ)\mathbf{s}^\star = \mathcal{T}(\mathbf{s}^\star; \boldsymbol{\theta}) of the update T\mathcal{T}. The gradient that NUTS needs comes from the implicit function theorem at that fixed point,

∂s⋆∂θ=(I2N−∂T∂s)−1∂T∂θ\frac{\partial \mathbf{s}^\star}{\partial \boldsymbol{\theta}} = \left(\mathbf{I}_{2N} - \frac{\partial \mathcal{T}}{\partial \mathbf{s}}\right)^{-1} \frac{\partial \mathcal{T}}{\partial \boldsymbol{\theta}}

which pyrox-ssm solves matrix-free with GMRES, whatever the number of iterations. It is the gradient of the evidence only when the iteration converged, which is why we pass reject_unconverged=True. Then we predict with the conditioned posterior q(f(t∗)∣y,θ)=N(μ∗,σ∗2)q(f(t_*) \mid \mathbf{y}, \boldsymbol{\theta}) = \mathcal{N}(\mu_*, \sigma_*^2) at any day t∗t_*, which the smoother gives from the same sites.

Route B, latent. We sample the log odds on the whole grid of TT days through the whitened innovations of Example 3b, zk∈RDx\mathbf{z}_k \in \mathbb{R}^{D_x}, zk∼N(0,IDx)\mathbf{z}_k \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_{D_x}), with Dx=2D_x = 2, and the Bernoulli likelihood is an ordinary NumPyro observation. NUTS samples p(θ,z1:T∣y)p(\boldsymbol{\theta}, \mathbf{z}_{1:T} \mid \mathbf{y}), that is 3+TDx3 + T D_x values, and every draw carries the path on the withheld days and the forecast. This posterior is exact, so we use Route B as the reference.

Setup

We detect Colab and install pyrox, pyrox-gp[colab] (which pulls in matplotlib and watermark) and pyrox-ssm only when the notebook runs there.

Python implementation: CPython
Python version       : 3.13.12
IPython version      : 9.13.0

jax       : 0.10.2
equinox   : 0.13.8
numpyro   : 0.21.0
optimistix: 0.1.0
gaussx    : 0.6.15
pyrox     : 0.2.1
pyrox_gp  : 0.2.0
pyrox_ssm : 0.1.0
matplotlib: 3.10.9

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. A record of wet and dry days

We simulate one station from the model itself, so that we know every true value: a Mediterranean-like climate whose wet season ends in spring. The record runs for N=90N = 90 days, from 1 April to 29 June, and we keep the T−N=15T - N = 15 days after it, to 14 July, for a forecast. On the seasonal mean alone the wet-day probability falls from about 0.4 on 1 April to about 0.03 on 29 June. The anomaly, with σf2=1\sigma_f^2 = 1 and ℓ=8\ell = 8 days, adds wet and dry spells of a week or two on top. Then we take days out as in Example 1: a 10-day logger outage in May, and each day missing at random with probability 0.1. A missed day is NaN in the station file, and we keep its true value to score the predictions. So the record runs from a wet regime into the sparse binary one, a few wet days among many dry ones, which is where a Gaussian approximation of the latent log odds is least comfortable.

T = 105 grid days, N = 90 record days, observed = 70, missing in the record = 20
  outage: 10 days, random dropouts: 10 days
  seasonal sigma(mu(t)): 0.412 on 1 April, 0.031 on 29 June
  April  true mean p = 0.530, observed wet days = 13 of 27
  May    true mean p = 0.097, observed wet days = 1 of 17
  June   true mean p = 0.181, observed wet days = 7 of 26
<Figure size 1200x400 with 1 Axes>

2. Route A: the path integrated out

Both routes share the priors, which we put in one function. The offset gets c∼N(−1,1.52)c \sim \mathcal{N}(-1, 1.5^2), so a station anywhere between much drier and much wetter than its climatology is plausible. The anomaly gets σf2∼LogNormal(0,1)\sigma_f^2 \sim \mathrm{LogNormal}(0, 1) and Example 1’s prior for the lengthscale, ℓ∼LogNormal(log⁡7,1)\ell \sim \mathrm{LogNormal}(\log 7, 1). The function returns the MarkovGPPrior with the seasonal mean as its mean_fn.

Route A then passes that prior, BernoulliLikelihood() and the record to markov_laplace_factor, which fits the sites with the strategy we give it and adds the approximate log evidence as a factor site named "y". The masked days, stored as NaN, get a zero site and never reach the arithmetic. With reject_unconverged=True the factor is −∞-\infty whenever the fit stops at max_iter without meeting its tolerance, so NUTS rejects that θ\boldsymbol{\theta} rather than move on an evidence and a gradient taken away from the fixed point.

site 'offset'         Normal         value shape=()
site 'variance'       LogNormal      value shape=()
site 'lengthscale'    LogNormal      value shape=()
site 'y'              factor         value shape=(0,)
unconstrained values for NUTS: 3

So Route A’s trace looks like Example 1’s: three scalar sample sites and one factor, and no latent path.

We do not use the strategy’s defaults (a full Newton step, damping=1.0, and max_iter=20). Without a line search a full Newton step can overshoot and oscillate when the prior variance is large, and then the fit stops at max_iter without converging. Under reject_unconverged=True that region of θ\boldsymbol{\theta} becomes a wall of −∞-\infty, which NUTS reports as divergences, and without it the factor there is an evidence and a gradient taken away from the fixed point. Below we fit both settings at four values of σf2\sigma_f^2, with cc and ℓ\ell at their true values, and print whether each fit converged and in how many iterations. Damping does not move the fixed point, so where both converge they give the same evidence, the damped one in more iterations.

strategy                                  σ_f² = 1      σ_f² = 4      σ_f² = 8     σ_f² = 16
defaults: damping 1.0, max_iter 20     converged 6   converged 8    stopped 20    stopped 20
damping 0.5, max_iter 50              converged 24  converged 25  converged 26  converged 27

With the defaults the fit converges in 6 and 8 iterations at σf2=1\sigma_f^2 = 1 and 4, but at σf2=8\sigma_f^2 = 8 and 16 it stops at max_iter without converging. The prior LogNormal(0,1)\mathrm{LogNormal}(0, 1) does not rule these values out, so NUTS would meet them. With a damping of 0.5 the fit converges at all four, in 24 to 27 iterations. So every Route A evaluation below pays for about four times as many smoother passes as an undamped fit, and in exchange its evidence is defined wherever NUTS goes.

3. Route B: the path sampled

Route B builds the same prior on the whole grid of TT days, the record and the forecast, and draws the log odds with markov_gp_innovations_sample("logit", prior), which registers the innovations as "logit_eps" and the path (mean included) as the deterministic site "logit". The observation is a plain NumPyro Bernoulli site, masked with .mask(mask) and with the days as its event dimension. NumPyro’s masked distribution still evaluates the log density on a masked day before it zeroes it, and a NaN there would turn the gradient into NaN, so Route B gets the record with 0 on the missed and forecast days, which are never read.

site 'offset'         Normal         value shape=()
site 'variance'       LogNormal      value shape=()
site 'lengthscale'    LogNormal      value shape=()
site 'logit_eps'      Normal         value shape=(105, 2)
site 'logit'          deterministic  value shape=(105,)
site 'y'              BernoulliLogits value shape=(105,)
unconstrained values for NUTS: 213

Route B’s trace holds the same three sample sites, the T×DxT \times D_x innovations, the deterministic path and the masked Bernoulli site, so NUTS moves 3+TDx=2133 + T D_x = 213 values.

4. NUTS on both routes

Route A has three values to sample, so, as in Example 1, we give it a dense mass matrix (dense_mass=True). Its log density is the expensive one (a damped Laplace fit and its implicit gradient), so we keep its run short, with 50 warm-up steps and 50 draws per chain. We also cap the tree depth at 4 (at most 15 leapfrog steps per draw), which is plenty for three values once the mass matrix is adapted. Route B has 213 values, so, as in Example 3b, only the three hyperparameters share a dense block of the mass matrix, and the innovations stay on the diagonal. Its log density is one scan, so it gets 150 warm-up steps and 150 draws per chain. Both routes run their chains one after the other with chain_method="sequential". We avoid "parallel", under which markov_gp_innovations_sample with its default Cholesky square root fails (issue #420). Both start at the prior medians, and the wall-clock times include JIT compilation.

A, Laplace    112.8 s,   6.8 leapfrog steps per draw, 1 divergences, smallest n_eff 50, largest r_hat 1.020
B, latent      31.2 s,  24.6 leapfrog steps per draw, 0 divergences, smallest n_eff 193, largest r_hat 1.004
Route A variance: median 1.10 over all draws, 0.46 over the divergent ones
Route A lengthscale: median 12.23 over all draws, 15.54 over the divergent ones

Both routes mix well enough for the comparison. Route A has one divergence in its 100 draws (at σf2=0.46\sigma_f^2 = 0.46 and ℓ=15.5\ell = 15.5 days, far from the large variances where the undamped fit failed), a largest R^\hat{R} of 1.020 and a smallest effective sample size of 50 over the three hyperparameters. Route B has no divergences, a largest R^\hat{R} of 1.004 and a smallest effective sample size of 193 from 300 draws. Route A needs 6.8 leapfrog steps per draw against Route B’s 24.6, as it samples three values instead of 213. However, its 100 draws took 112.8 s, against 31.2 s for Route B’s 300.

5. The hyperparameters against the truth

For each hyperparameter we print the posterior mean, standard deviation and 90 % interval of each route, next to the value we simulated the record with.

parameter      truth    A, Laplace mean ± sd            90% interval     B, latent mean ± sd            90% interval
offset         -1.50         -0.780 ± 0.581   [ -2.014,   0.096]  in         -0.719 ± 0.654   [ -1.772,   0.137]  in
variance        1.00          1.353 ± 0.991   [  0.275,   3.364]  in          1.684 ± 1.418   [  0.307,   4.570]  in
lengthscale     8.00         12.524 ± 6.372   [  4.339,  25.082]  in         11.800 ± 7.803   [  3.253,  26.898]  in
<Figure size 1300x330 with 3 Axes>

Both routes have all three true values inside their 90 % intervals, and they agree on the offset (cc = −0.78 ± 0.58 for Route A, −0.72 ± 0.65 for Route B) and on the lengthscale (12.5 ± 6.4 against 11.8 ± 7.8 days). Both put the offset above the true −1.5 and the lengthscale above the true 8 days. Since the two routes agree, this belongs to the record (70 observed wet or dry days say little about either), not to the method. They differ in the variance. Route A’s posterior of σf2\sigma_f^2 has a mean of 1.35 and a 90 % interval up to 3.36, Route B’s a mean of 1.68 and an interval up to 4.57. So the Laplace evidence trims the upper tail of σf2\sigma_f^2. With 100 draws the histograms of Route A are rough, but the difference is in the place where we would expect the Gaussian approximation to be worst, as a larger σf2\sigma_f^2 puts more of the log odds where the logistic function saturates.

6. The wet-day probability through the gaps and the forecast

Route B’s draws e∈Ee \in \mathcal{E} carry the log odds on every day of the grid, so its wet-day probability is pk(e)=σ(μ(e)(tk)+f(e)(tk))p_k^{(e)} = \sigma(\mu^{(e)}(t_k) + f^{(e)}(t_k)), with no extra step, as in Example 3b. Route A’s draws carry only θ(e)\boldsymbol{\theta}^{(e)}. For each of NE=100N_{\mathcal{E}} = 100 of them we refit the Laplace sites with condition_nongauss and call predict at all TT days of the grid, which gives the Gaussian q(μ(tk)+f(tk)∣y,θ(e))=N(μk(e),(σk(e))2)q(\mu(t_k) + f(t_k) \mid \mathbf{y}, \boldsymbol{\theta}^{(e)}) = \mathcal{N}(\mu_k^{(e)}, (\sigma_k^{(e)})^2), also on the withheld days and the forecast, where the smoother runs its predict step only. The wet-day probability is a nonlinear function of the log odds, so we draw NMC=20N_\text{MC} = 20 log odds from each Gaussian, push them through σ(⋅)\sigma(\cdot) and pool the NENMCN_{\mathcal{E}} N_\text{MC} values. For both routes we then summarise pkp_k by its posterior mean, which is also the predictive probability of a wet day, P(yk=1∣y)\mathbb{P}(y_k = 1 \mid \mathbf{y}), and by the 2.5 % and 97.5 % quantiles, the 95 % band.

Route A prediction for 100 draws at 105 days: 5.9 s (with JIT); Laplace fits converged for 100 of 100 draws, in 24.7 iterations on average (at most 27)

The top panel shows the wet-day probability: Route B’s 95 % band and mean in blue, Route A’s band (dashed) and mean in orange, the true pkp_k as a thin black line, the observed days as ticks at 0 and 1 and the withheld days as red crosses. The outage is shaded and the forecast starts at the dotted line. A probability near zero squeezes every band together, so the bottom panel shows the same quantiles on the log-odds scale, where the dry end of the record is visible.

<Figure size 1200x800 with 2 Axes>

The two routes give almost the same picture. Both posterior means smooth the wet and dry days into a wet spell in April, a dry May and a smaller wet spell in June, and both bands hold the true pkp_k on nearly every day. Through the outage and in the forecast the bands widen, and in the forecast they relax towards the seasonal mean and the stationary spread of the anomaly, as the Gaussian bands did in Example 1. The visible difference is in May. On the log-odds scale Route A’s band sits a little above Route B’s through the run of dry days after the outage, and section 7 shows where that comes from.

Because the record is simulated, we know pkp_k on every day and whether each withheld day was wet. A 95 % predictive interval for a single 0 or 1 is not a useful check, since it holds both outcomes unless P(yk=1∣y)\mathbb{P}(y_k = 1 \mid \mathbf{y}) is below 2.5 % or above 97.5 %. So we score each route in two ways. The first is the fraction of days on which the true pkp_k is inside the 95 % band (the coverage of the latent probability). The second, on the withheld days and the forecast, is the mean log predictive density, 1Nsel∑klog⁡P(yk∣y)\frac{1}{N_\text{sel}} \sum_k \log \mathbb{P}(y_k \mid \mathbf{y}) over the NselN_\text{sel} selected days (higher is better), and the Brier score, 1Nsel∑k(P(yk=1∣y)−yk)2\frac{1}{N_\text{sel}} \sum_k (\mathbb{P}(y_k = 1 \mid \mathbf{y}) - y_k)^2 (lower is better). The scores of the true pkp_k are the best that any model of these days can do on average.

days                     n   p in 95% band       log predictive density              Brier score
                                 A       B          A       B   truth           A      B   truth
observed days           70   95.7%  100.0%
isolated dropouts       10   90.0%  100.0%     -0.610  -0.594  -0.619       0.214  0.208   0.210
outage (5-14 May)       10  100.0%  100.0%     -0.303  -0.291  -0.136       0.070  0.066   0.018
forecast                15  100.0%  100.0%     -0.246  -0.257  -0.218       0.062  0.064   0.059

On the 70 observed days the true pkp_k is inside Route B’s 95 % band on every day and inside Route A’s on 95.7 % of them. On the outage and the forecast both bands hold it on every day, and on the 10 isolated dropouts Route B’s does on all of them and Route A’s on 9 (90.0 %). The scores of the predictive probabilities differ by at most 0.016 in log predictive density (−0.303 for Route A against −0.291 for Route B on the outage, −0.246 against −0.257 on the forecast), and the Brier scores by at most 0.006. The true pkp_k scores much better on the outage (−0.136), where neither model can know the path. On the isolated dropouts it scores a little worse than both (−0.619), which with 10 days is noise.

7. Where the Laplace approximation is biased

Route A approximates in two places. Its hyperparameter posterior comes from the approximate evidence, and for each θ\boldsymbol{\theta} its latent posterior is a Gaussian q(f∣y,θ)q(\mathbf{f} \mid \mathbf{y}, \boldsymbol{\theta}) centred at the mode. To separate the two, we condition on Route B’s own hyperparameter draws: for NE=100N_{\mathcal{E}} = 100 of them we fit the Laplace sites and, for comparison, the EP sites of ExpectationPropagationMarkov, and compare the resulting latent posteriors with Route B’s, which is exact for the same draws. Any difference is then the error of the Gaussian approximation alone. We compare the posterior mean and standard deviation of the log odds μ(tk)+f(tk)\mu(t_k) + f(t_k), mixed over the draws as in Example 1, in each month of the record: the wet start in April, May with the outage and a long dry run, and the dry June.

Laplace and EP fits for 100 Route B draws: 6.5 s
  Laplace | θ_B  converged 100 of 100, 24.9 iterations
  EP | θ_B       converged 100 of 100, 21.5 iterations

latent posterior                  mean − B mean                      sd / B sd
                        April      May     June        April      May     June
Laplace | θ_B          -0.002    0.152    0.063         0.95     0.96     0.98
EP | θ_B               -0.010    0.036   -0.026         0.98     1.01     0.99
A, Laplace             -0.047    0.141    0.015         0.89     0.87     0.93
<Figure size 1200x650 with 2 Axes>

With Route B’s own hyperparameters, the Laplace posterior of the log odds matches Route B’s in April (a mean difference of −0.002 and a standard deviation ratio of 0.95) and in June (0.063 and 0.98). In May it does not. There the record holds 1 wet day in 17 observed days, and the Laplace mean sits on average 0.152 above Route B’s, most of all in the run of dry days after the outage (top panel). EP at the same hyperparameters stays within 0.036 of Route B in May and within 0.026 in the other months. This is the sparse binary case. A run of dry days skews the posterior of the log odds, with a long tail towards very negative values (a dry day says little about how dry the day was). A Gaussian centred at the mode then sits above the mean of such a distribution. EP matches the mean and variance of the tilted distribution at each site, rather than the curvature at the mode, so it follows the skew.

Route A’s own posterior (dotted) also carries its trimmed σf2\sigma_f^2. Its bands are narrower than Route B’s in every month (standard deviation ratios of 0.89, 0.87 and 0.93), whereas the Laplace bands at Route B’s hyperparameters are not (0.95 to 0.98). So in this example the Laplace approximation costs Route A a shift of about 0.14 in the log odds where the data are sparse, and somewhat narrower bands through the hyperparameters. Both are small next to the width of the bands, which is why the coverage and the scores of section 6 barely differ.

8. Cost

We compare the two routes in three ways. First, the time of one jitted log density and its gradient, at the prior medians and with Route B’s innovations at zero. Second, the NUTS wall-clock time and the leapfrog steps per draw from section 4. Third, the smallest effective sample size over the three hyperparameters per second of NUTS, which is the number that decides which route is cheaper for θ\boldsymbol{\theta}.

route         grad, ms   NUTS, s  steps/draw  draws  min n_eff  n_eff / s
A, Laplace       32.33     112.8         6.8    100         50       0.44
B, latent         0.62      31.2        24.6    300        193       6.21

Route A prediction: 5.9 s (100 draws x 105 days)
Laplace and EP at Route B's draws: 6.5 s

One log density and its gradient cost 32.3 ms for Route A and 0.62 ms for Route B, about fifty times more. Route A runs the damped fixed-point iteration to convergence (about 25 smoother passes here, from section 6) and then solves the implicit adjoint with GMRES, each step of which is another pass. Route B runs one scan over the 105 days and its reverse pass. Route A makes up some of this in the number of steps, 6.8 leapfrog steps per draw against 24.6, because it samples three values rather than 213. Per draw that is still about fourteen times the work of Route B, and per effective sample of the hyperparameters Route B is ahead by a similar factor, 6.21 against 0.44 per second (both including JIT compilation). So on a CPU and at this record length the sampled path is the cheaper route to the hyperparameters. Route A gives the smaller posterior: three values, few steps per draw, and no mass matrix to adapt over the path.

Summary

  • A Bernoulli model on a Markov GP is a plain NumPyro function either way. Route A calls markov_laplace_factor(..., strategy=LaplaceMarkovInference(damping=0.5, max_iter=50), mask=mask, reject_unconverged=True), so its trace holds three sample sites and one factor. Route B calls markov_gp_innovations_sample and adds a masked Bernoulli site, so NUTS moves 213 values.

  • The strategy’s defaults (a full Newton step, 20 iterations) stop without converging at σf2=8\sigma_f^2 = 8 and 16 on this record. A damping of 0.5 converged at all four values we checked, in 24 to 27 iterations.

  • The two routes agree on the offset and the lengthscale, and both hold all three true values in their 90 % intervals. The Laplace evidence trims the upper tail of σf2\sigma_f^2 (a 90 % interval up to 3.36, against 4.57 for Route B).

  • Route A’s prediction, condition_nongauss(...).predict(...) averaged over 100 NUTS draws, follows Route B’s through the outage and the forecast. Both bands hold the true pkp_k on every outage and forecast day, and the log predictive densities differ by at most 0.016.

  • The Laplace latent posterior is close to exact where the data are informative (April, June) and 0.152 too high in the log odds in May, the sparse month with 1 wet day in 17, where EP stays within 0.036.

  • Route A costs 32.3 ms per gradient against 0.62 ms and needs 6.8 leapfrog steps per draw against 24.6, so here Route B gives 6.21 effective samples per second against 0.44.

For the four site-based strategies at fixed hyperparameters see Non-Gaussian Markov GP inference, for whitened paths in a spatial model Example 3b, and for the Gaussian case with the Kalman filter Example 1.