Skip to main content

WeftMC: Variational Coordinate Warps, Standalone VI, and Where It Beats or Trails Stan

A look inside WeftMC across MCMC and standalone variational inference: moving precision charts, score-matching diagnostics, mini-batch WAIVES and SVRG-Stein, and step-by-step reparameterization case studies on ctsem state-space and SIR ODE models.
stan
mcmc
variational-inference
hierarchical-models
Author

Sean Pinkney

Published

December 3, 2026

1. Introduction

WeftMC is a C++17 and Python library built on one idea: fit a variational approximation to the posterior first, measure how good it is, and let that measurement choose the sampler. It evaluates Stan models in memory through BridgeStan (Roualdes et al. 2023) and also accepts targets written in Python. It has two pipelines.

Markov chain Monte Carlo (weftmc.sample). Each chain fits its own warp: an invertible map \(x = T_c(z)\) that carries a simple reference distribution in \(z\) onto an approximation of the posterior in \(x\). The chain scores its warp with the Pareto-smoothed importance sampling (PSIS) shape estimate \(\hat{k}_c\) (Zhang and Stephens 2009; Vehtari et al. 2024), which measures how heavy the right tail of the importance ratios between posterior and approximation is. If \(\hat{k}_c < 0.5\), the warp is accurate enough to serve as a proposal distribution, and the chain runs batched multiple-try Metropolis with exact evaluation of the target. If \(\hat{k}_c \ge 0.5\), the warp leaves part of the posterior mass out of reach, and the chain uses symplectic or harmonic-split trajectory sampling in the warped space instead. Chains share no information during adaptation, so the split rank-normalized \(\widehat{R}\) (Vehtari et al. 2021) remains a valid convergence monitor.

Standalone variational inference and structural diagnostics (weftmc.fit_vi, weftmc.diagnose). fit_vi fits an \(O(dr)\) Gaussian or triangular approximation, for \(d\) parameters and a rank-\(r\) factor, with no MCMC. It runs on multi-threaded BridgeStan models or on mini-batch streams over large \(N\). diagnose reads the fitted precision factor and the parameter constraints and reports what is wrong with the geometry: collinearity ridges, partial-centering weights, funnel couplings, and lever-arm distortions from nonlinear links or boundaries.

The name comes from weaving: a Monte Carlo sample is the weft drawn across a variational warp (Parno and Marzouk 2018; Hoffman et al. 2019).

Sections 2 and 3 describe what is new in each pipeline and benchmark it against CmdStan 2.40.0, on PosteriorDB models and on models from Stan Discourse, including the cases where CmdStan wins. Sections 4 and 5 are step-by-step examples of diagnosing and reparameterizing two continuous-time model families: four state-space models from ctsem (Driver et al. 2017; Driver 2026) and a nonlinear SIR epidemic model defined by ordinary differential equations (Novik 2022; Chatzilena et al. 2019). Section 6 summarizes when to use what.

2. Markov Chain Monte Carlo

2.1 What Is New

Three mechanisms separate weftmc.sample from Hamiltonian Monte Carlo (HMC) with a fixed metric, meaning a constant mass matrix, and from Pathfinder-initialized HMC.

1. PSIS \(\hat{k}\) Routing to Density-Only Multiple-Try Metropolis

Whether a warp \(T_c\) covers the target \(\pi\) is judged as in Yao et al. (2018). WeftMC draws \(z_m\) from a base distribution \(g\) and forms the log importance ratios

\[ \log w_m = \log\pi(T_c(z_m)) + \log|\det J_{T_c}(z_m)| - \log g(z_m), \]

the log density of the target pulled back to \(z\)-space, minus the log density the draws came from. PSIS fits a generalized Pareto distribution to the largest ratios and reports its shape \(\hat{k}\). Such a tail has finite moments only of order below \(1/k\), so the importance weights have finite variance when \(\hat{k} < 0.5\).

Pathfinder (Zhang et al. 2022) stops at static importance resampling of its draws, which caps the effective sample size (ESS) below the number of pilot draws. WeftMC uses the warp as a proposal instead. When every chain reaches \(\hat{k}_c < 0.5\) and \(\widehat{\mathrm{ESS}}_{\mathrm{PSIS}}/M \ge 0.50\) on \(M = 1{,}024\) draws from the two-component mixture \(g(z) = 0.93\,\mathcal{N}(0, I_d) + 0.07\,t_6(0, 1.25^2 I_d)\) of a standard normal and an isotropic multivariate \(t_6\) distribution, it runs the multiple-try Metropolis algorithm of Liu, Liang, and Wong (Liu et al. 2000) (variational_mtm). Each step draws a batch of \(K\) candidates from the warp, selects one with probability proportional to its weight, and accepts or rejects it with a ratio that leaves \(\pi\) invariant. Proposals need only log_density evaluations, so there are no reverse-mode autodiff sweeps, and the output is an exact, unweighted Markov chain.

A mode-centered fit can miss slightly on a skewed posterior. When \(\hat{k}_c \in [0.5, 0.95]\), WeftMC runs a trajectory burst of 75–150 steps and refits the location and scale \((m, B_0)\) from the burst’s states and gradients, with zero extra target calls. The refit has two variance estimates along each eigenvector \(w_a\) of the secant precision \(P_{\mathrm{sec}} = W\operatorname{diag}(\lambda_{\mathrm{sec}})W^\top\), which is built from gradient differences along the burst: the inverse curvature \(\lambda_{\mathrm{sec}, a}^{-1}\) and the empirical variance of the burst states, \(v_{\mathrm{emp}, a} = w_a^\top \Sigma_{\mathrm{emp}}\, w_a\). Averaging them fails in both regimes that matter. A short burst that has not yet traversed a slow ridge underestimates the variance (\(v_{\mathrm{emp}, a} \ll \lambda_{\mathrm{sec}, a}^{-1}\)), and heavy tails stretch it past what the local curvature implies (\(v_{\mathrm{emp}, a} > \lambda_{\mathrm{sec}, a}^{-1}\)). In each regime the larger estimate is the better one, so WeftMC takes the maximum, with a 6% margin on the scale:

\[ \sigma_{\mathrm{env}, a}^2 = 1.06^2 \max\!\left(\lambda_{\mathrm{sec}, a}^{-1},\; w_a^\top \Sigma_{\mathrm{emp}}\, w_a\right). \]

This upper envelope dominates the secant covariance in the Loewner order (Löwner 1934), in which \(A \succeq B\) means \(A - B\) is positive semidefinite, and is at least as wide as the burst in every eigendirection. WeftMC then re-checks \(\hat{k}_c < 0.5\).

2. Avoiding the Frozen Dense-Metric Trap

On the varying-slope models pupil_fit4 and pupil_fit5, stan_dense and stan_pathfinder_dense (CmdStan’s dense metric, without and with Pathfinder initialization) stall at \(\widehat{R} \in [1.58, 3.00]\) while diagonal HMC converges. A dense metric exists to handle correlated posteriors, so why does it lose to a diagonal one? Because the correlation it learns is right at only one value of the group scale. Consider a non-centered varying-intercept predictor with log scale \(\ell = \log\tau\) and no sum-to-zero constraint on the group effects:

\[ \eta_n = \alpha + e^{\ell} z_{g[n]}, \qquad z_j \sim \mathcal{N}(0, 1). \]

At any fixed scale \(\ell_0\), shifting \(\alpha \mapsto \alpha + \delta\) and every \(z_j \mapsto z_j - e^{-\ell_0}\delta\) leaves each \(\eta_n\) unchanged. The likelihood is flat along that direction and only the prior on \(z\) bounds it, so the posterior has a long translation ridge. A constant dense or low-rank affine preconditioner fitted at \(\ell_0\) learns this ridge. In its whitened coordinates \((u_0, u_1, \dots, u_J)\) the map is

\[ \alpha = m_\alpha + \sigma_\alpha u_0, \qquad z_j = m_{z,j} - e^{-\ell_0}\sigma_\alpha u_0 + \sigma_{\mathrm{cond}, j} u_j, \]

so \(u_0\) moves along the ridge. Here \(\sigma_\alpha\) is the marginal standard deviation of \(\alpha\), \(\sigma_{\mathrm{cond}, \alpha}\) is its standard deviation with \(z\) held fixed, and \(\rho_\alpha = \sigma_\alpha / \sigma_{\mathrm{cond}, \alpha} \gg 1\) is the ridge inflation ratio.

The map is frozen but the ridge is not: its direction depends on \(\ell\). Substituting the frozen map into \(\eta_n\) at any other log scale \(\ell \ne \ell_0\) gives

\[ \eta_n(u, \ell) = m_\alpha + e^{\ell} m_{z,g[n]} + \sigma_\alpha\!\left(1 - e^{\ell - \ell_0}\right) u_0 + e^{\ell}\sigma_{\mathrm{cond}, g[n]} u_{g[n]}. \]

The \(u_0\) term cancels only at \(\ell = \ell_0\). Anywhere else, a unit step in \(u_0\) shifts every \(\eta_n\) by \(\sigma_\alpha(1 - e^{\ell - \ell_0})\), exactly as shifting \(\alpha\) by that amount with \(z\) fixed would. The likelihood resists such a shift with precision \(\sigma_{\mathrm{cond}, \alpha}^{-2}\), so the precision along \(u_0\), which is 1 at the pilot scale, becomes

\[ \kappa_{u_0}(\ell) \approx 1 + \rho_\alpha^2 \left(1 - e^{\ell - \ell_0}\right)^2. \]

At \(\rho_\alpha = 24\) (pm25_cluster_region) and \(\rho_\alpha = 52\) (park_rule), a drop of 0.5 in \(\ell\) inflates the curvature 90x and 420x, and a rise of 0.5 inflates it 243x and 1,139x. A step size tuned for unit curvature cannot cross that wall, so each chain stays near the scale at which its metric was fitted, and chains fitted at different pilot scales do not mix (Figure 1). A diagonal metric has no off-diagonal terms to go stale, which is why stan_diag converges on these models.

WeftMC’s first defense is a transport that moves with the scale (mechanism 3 below). When that nonlinear transport is declined on \(d \ge 12\) and the dispersion of held-out log ratios indicates scale variation, WeftMC strips the frozen off-diagonal terms (diagonal_fallback) and adapts diagonal scales across warmup windows.

Code
library(ggplot2)
library(patchwork)
library(knitr)
source("../../R/theme_blog.R")

disc <- read.csv("discourse-41542-results.csv", stringsAsFactors = FALSE, na.strings = "NA")

ell_grid <- seq(-0.8, 0.8, length.out = 301)
curve_df <- rbind(
  data.frame(delta_ell = ell_grid, kappa = 1 + 10^2 * (1 - exp(ell_grid))^2, family = "Frozen dense (rho = 10, loss_nl)"),
  data.frame(delta_ell = ell_grid, kappa = 1 + 24^2 * (1 - exp(ell_grid))^2, family = "Frozen dense (rho = 24, pm25)"),
  data.frame(delta_ell = ell_grid, kappa = 1 + 52^2 * (1 - exp(ell_grid))^2, family = "Frozen dense (rho = 52, park_rule)"),
  data.frame(delta_ell = ell_grid, kappa = rep(1.0, length(ell_grid)), family = "Moving Woodbury P(h) / s2z")
)
curve_df$family <- factor(curve_df$family, levels = unique(curve_df$family))

p_trap <- ggplot(curve_df, aes(x = delta_ell, y = kappa, color = family, linetype = family)) +
  geom_vline(xintercept = 0, linetype = "dotted", color = blog_colors$text_light, linewidth = 0.5) +
  geom_line(linewidth = 1.0) +
  scale_y_log10(
    breaks = c(1, 10, 100, 1000, 10000),
    labels = c("1x", "10x", "100x", "1,000x", "10,000x")
  ) +
  scale_color_manual(values = c(blog_colors$gold, blog_colors$purple, blog_colors$red, blog_colors$teal)) +
  scale_linetype_manual(values = c("solid", "solid", "solid", "dashed")) +
  labs(
    title = "Curvature Wall Away From Pilot Scale",
    subtitle = "Precision spike on u0 under a frozen dense metric",
    x = "Log-scale shift (ell - ell_0)",
    y = "Whitened precision on u0 (log)",
    color = NULL,
    linetype = NULL
  ) +
  theme_blog(base_size = 10.5) +
  theme(legend.position = "bottom", legend.direction = "vertical")

p4 <- subset(disc, case_id == "pupil_fit4" & arm_key %in% c("weftmc", "stan_diag", "stan_dense", "stan_pathfinder"))
p4$arm_label <- factor(
  p4$arm_key,
  levels = c("stan_dense", "stan_pathfinder", "stan_diag", "weftmc"),
  labels = c("CmdStan dense_e\n(626 divs)", "CmdStan PF + dense_e\n(19 divs)", "CmdStan diag_e\n(0 divs)", "WeftMC\n(0 divs)")
)
p4$status <- ifelse(p4$max_rhat <= 1.05, "Converged (R-hat <= 1.01)", "Stalled (R-hat > 2.8)")

p_pupil <- ggplot(p4, aes(x = max_rhat, y = arm_label, fill = status)) +
  geom_col(width = 0.58) +
  geom_vline(xintercept = 1.01, linetype = "dashed", color = blog_colors$text, linewidth = 0.5) +
  geom_text(
    aes(label = sprintf("R-hat = %.3f", max_rhat)),
    hjust = ifelse(p4$max_rhat > 1.5, 1.08, -0.08),
    color = ifelse(p4$max_rhat > 1.5, "white", blog_colors$text),
    size = 3.3,
    fontface = "bold"
  ) +
  scale_x_continuous(limits = c(0, 3.35), breaks = c(0, 1, 2, 3)) +
  scale_fill_manual(values = c("Converged (R-hat <= 1.01)" = blog_colors$teal, "Stalled (R-hat > 2.8)" = blog_colors$red)) +
  labs(
    title = "pupil_fit4 (d = 47)",
    subtitle = "Frozen off-diagonal metrics stall; diagonal & WeftMC converge",
    x = "Worst rank-normalized R-hat",
    y = NULL,
    fill = NULL
  ) +
  theme_blog(base_size = 10.5) +
  theme(legend.position = "bottom", legend.direction = "vertical")

p_trap | p_pupil
Figure 1: Why frozen dense metrics stall on uncentered hierarchical ridges. Left: whitened precision \(\kappa_{u_0}(\ell) = 1 + \rho_\alpha^2 (1 - e^{\ell - \ell_0})^2\) as \(\ell\) moves away from pilot scale \(\ell_0\) at ridge ratios \(\rho_\alpha \in \{10, 24, 52\}\) matching loss_nl_log_corr, pm25_cluster_region, and park_rule; a moving Woodbury chart or sum-to-zero reparameterization keeps \(\kappa_{u_0}(\ell) \equiv 1\). Right: worst \(\widehat{R}\) on pupil_fit4 (\(d=47\)), where stan_dense and stan_pathfinder_dense stall above \(2.8\) while stan_diag and WeftMC converge with 0 divergences.

3. Antithetic Funnel Discovery, Moving Woodbury Frames, and GIST Splitting

A funnel (Neal 2003; Papaspiliopoulos et al. 2007) is a posterior in which a parent parameter \(h\) sets the scale of a block of children, typically as \(e^{h}\). WeftMC has no access to Stan’s syntax tree, so it finds these scale parents numerically, in 48 gradient evaluations. It draws probes \(e^{(k)} \sim \mathcal{N}(0, I_d)\) and evaluates the gradient at the antithetic pairs \(m \pm B_0 e^{(k)}\) around the mode. For a centered child \(x_j \mid h \sim \mathcal{N}(0, e^{2h})\) (mode \(0\)), the gradient component is \(-x_j e^{-2h}\), with log magnitude \(\log|x_j| - 2h\). The term \(\log|x_j|\) is the same at both points of a pair, because the children are displaced symmetrically about \(0\), so it cancels in the difference and leaves a term linear in the parent’s displacement. Coordinates whose log gradient magnitudes track a parent block \(h \in \mathbb{R}^p\) this way are the ones whose scale varies exponentially with it.

Finding the parent is half the job. The transport must also let the precision of the children’s conditional distribution, the fiber over \(h\), move with \(h\), and recomputing a dense precision at every leapfrog step would cost \(O(d^3)\). WoodburyConditionalTransport (transport="woodbury") parameterizes the fiber precision as a fixed diagonal plus a rank-\(r\) term whose row scales depend on \(h\):

\[ P(h) = \Lambda_0 + W(h) W(h)^\top, \qquad W(h) = \operatorname{diag}(a(h))\,U_r. \]

By the Woodbury identity (Woodbury 1950), everything expensive about \(P(h)\) reduces to the \(r \times r\) capacitance matrix \(C(h) = I_r + W(h)^\top \Lambda_0^{-1} W(h)\): the inverse is \(P^{-1} = \Lambda_0^{-1} - \Lambda_0^{-1} W C^{-1} W^\top \Lambda_0^{-1}\) and the determinant is \(\det P = \det\Lambda_0 \, \det C\). WeftMC updates both \(P(h)^{-1/2}\) and \(\log|\det J_T(z)|\) in \(O(d \cdot r^2 + r^3)\) this way, and differentiates through the matrix functions with Loewner’s divided-difference formula (Löwner 1934).

When trajectory sampling is required (\(\hat{k} \ge 0.5\)), WeftMC pairs a symplectic No-U-Turn Sampler (NUTS) with GistSplitKernel. In warped coordinates the target is close to a standard normal, so the Hamiltonian is close to the isotropic Gaussian reference \(\tfrac{1}{2}\|z\|^2 + \tfrac{1}{2}\|p\|^2\), whose flow is an exact rotation of each position and momentum pair. The kernel applies that rotation analytically (Beskos et al. 2011; Shahbaba et al. 2014), which leaves only the residual for the numerical integrator. It adapts local step sizes by Gibbs self-tuning (GIST) (Bou-Rabee et al. 2024, 2025): the step size is drawn as an auxiliary variable conditional on the current state, so adapting it locally keeps the chain exact.

2.2 MCMC Results Against CmdStan 2.40.0

I ran two MCMC suites, each with 4 chains and 1,000 retained draws per chain, comparing WeftMC (kernel="auto") against three CmdStan 2.40.0 configurations: diag_e (stan_diag), dense_e (stan_dense), and 4-path Pathfinder followed by dense_e (stan_pathfinder_dense). Throughput is ESS/s: the minimum ESS over parameters per wall-clock second.

PosteriorDB holdout suite (6 models \(\times\) 2 seeds = 12 runs; Figure 2 and Table 1). None of these models was used to tune thresholds. All 12 WeftMC runs reach \(\widehat{R} \le 1.002\), pass \(\hat{k} < 0.5\), and switch to density-only variational_mtm. Eight pass immediately. The other four, on dogs and mesquite, pass after a short burst and envelope refit. Relative to CmdStan, WeftMC’s ESS/s is

  • 2.3x–258.9x that of stan_diag (ahead on all 12 runs),
  • 0.92x–115.8x that of stan_dense (ahead on 11 of 12),
  • 0.72x–185.9x that of stan_pathfinder_dense (ahead on 10 of 12).
Code
hold <- read.csv("holdout-comparison.csv", stringsAsFactors = FALSE)
hold$label_name <- paste0(hold$short_name, " (d=", hold$dimension, ")")

w_df <- subset(hold, arm_key == "weftmc")[, c("case_id", "seed", "ess_per_second")]
names(w_df)[3] <- "weft_ess_s"

st_df <- subset(hold, arm_key %in% c("stan_diag", "stan_dense", "stan_pathfinder_dense"))
m_df <- merge(st_df, w_df, by = c("case_id", "seed"))
m_df$ratio <- m_df$weft_ess_s / m_df$ess_per_second

m_dense <- subset(m_df, arm_key == "stan_dense")
ord_tbl <- aggregate(ratio ~ label_name, data = m_dense, FUN = min)
ord_levels <- ord_tbl$label_name[order(ord_tbl$ratio)]
m_df$label_name <- factor(m_df$label_name, levels = ord_levels)
m_df$baseline_label <- factor(
  m_df$arm_key,
  levels = c("stan_dense", "stan_diag", "stan_pathfinder_dense"),
  labels = c("vs CmdStan dense_e", "vs CmdStan diag_e", "vs CmdStan PF + dense_e")
)

ggplot(m_df, aes(x = ratio, y = label_name, color = baseline_label, shape = factor(seed))) +
  geom_vline(xintercept = 1.0, linetype = "dashed", color = blog_colors$text, linewidth = 0.55) +
  geom_point(size = 2.9, alpha = 0.92, position = position_dodge(width = 0.45)) +
  scale_x_log10(
    breaks = c(0.5, 1, 2, 5, 10, 25, 50, 100, 250),
    labels = c("0.5x", "1x", "2x", "5x", "10x", "25x", "50x", "100x", "250x")
  ) +
  scale_color_manual(values = c(blog_colors$blue, blog_colors$purple, blog_colors$gold)) +
  scale_shape_manual(values = c(16, 17), labels = c("Seed 1", "Seed 2")) +
  guides(color = guide_legend(nrow = 1), shape = guide_legend(nrow = 1)) +
  labs(
    title = "PosteriorDB Holdout Suite: Relative ESS/s (6 Models x 2 Seeds)",
    subtitle = "Right of dashed 1x line favors WeftMC",
    x = "WeftMC min ESS/s divided by CmdStan 2.40.0 min ESS/s (log scale)",
    y = NULL,
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 10.5) +
  theme(legend.position = "bottom", legend.box = "vertical")
Figure 2: Throughput ratio (WeftMC min ESS/s divided by CmdStan 2.40.0 min ESS/s, log scale) across all 12 PosteriorDB holdout runs (holdout-comparison.csv, 6 models \(\times\) 2 seeds). Every run passes PSIS \(\hat{k} < 0.5\) and switches to density-only variational_mtm.
Code
agg_hold <- aggregate(
  cbind(wall_seconds, ess_per_second) ~ short_name + dimension + arm_key,
  data = hold,
  FUN = median
)
wide_sec <- reshape(
  agg_hold,
  idvar = c("short_name", "dimension"),
  timevar = "arm_key",
  direction = "wide"
)
wide_sec <- wide_sec[order(-wide_sec$dimension, wide_sec$short_name), ]

disp_hold <- data.frame(
  Model = wide_sec$short_name,
  d = wide_sec$dimension,
  `WeftMC (s)` = sprintf("%.2f", wide_sec$wall_seconds.weftmc),
  `Stan dense (s)` = sprintf("%.2f", wide_sec$wall_seconds.stan_dense),
  `WeftMC ESS/s` = sprintf("%.1f", wide_sec$ess_per_second.weftmc),
  `Stan diag ESS/s` = sprintf("%.1f", wide_sec$ess_per_second.stan_diag),
  `Stan dense ESS/s` = sprintf("%.1f", wide_sec$ess_per_second.stan_dense),
  `Stan PF+dense ESS/s` = sprintf("%.1f", wide_sec$ess_per_second.stan_pathfinder_dense),
  check.names = FALSE
)

kable(disp_hold, row.names = FALSE, align = c("l", "r", "r", "r", "r", "r", "r", "r"))
Table 1: PosteriorDB holdout benchmark (holdout-comparison.csv; median across 2 seeds, 4 chains \(\times\) 1,000 draws).
Model d WeftMC (s) Stan dense (s) WeftMC ESS/s Stan diag ESS/s Stan dense ESS/s Stan PF+dense ESS/s
mesquite 8 0.21 1.40 16511.0 1589.7 4632.8 18749.2
earnings 5 1.39 2.92 3297.9 807.5 2178.3 2732.6
kilpisjarvi_mod 3 0.09 4.25 50517.6 255.8 608.2 296.7
radon_mn 3 0.79 2.01 8530.2 2612.1 3010.3 3905.4
dogs 2 1.20 2.34 4364.5 1358.2 2181.6 2254.6
nes_logit_data 2 0.23 0.66 30005.8 2346.7 13447.5 13483.3

Hierarchical and nonlinear stress suite (13 models from Stan Discourse topic 41542; Figure 3). All 13 baseline models (non-s2z, meaning without sum-to-zero constraints) have \(\hat{k} \ge 0.5\) and route to trajectory sampling. The outcomes fall into four groups.

Small-\(J\) funnels: WeftMC wins. On the three centered random-effects meta-analyses with few groups (rbest_dmap_j2 through rbest_dmap_j4), CmdStan’s three configurations record 146–463 divergences per run, 2,667 in total, inside the \(\tau \to 0\) funnel. WeftMC finishes all three models with 0 divergences and \(\widehat{R} \le 1.021\). Passing transport="woodbury" on rbest_dmap_j4 raises tail/bulk ESS 3.2x, from 56.6 to 178.7.

Frozen-metric stalls: WeftMC wins. On pupil_fit4 (\(d = 47\)), pupil_fit5 (\(d = 67\)), and pm25_cluster_log_region (\(d = 18\)), stan_dense and stan_pathfinder_dense hit the stall of Section 2.1, with \(\widehat{R}\) of 1.05–3.00 and 19–773 divergences. WeftMC’s diagonal_fallback converges with 0 divergences and beats stan_diag in ESS/s: 0.82 vs 0.63, 0.56 vs 0.45, and 1.22 vs 1.19.

Large or walled models: CmdStan diag_e wins. When diagonal_fallback strips the off-diagonal preconditioning on larger models (phylo_cov, \(d = 204\); park_rule, \(d = 2{,}442\)), or when the unconstrained space has hard NaN walls (loss_nl_uncorr), single-binary CmdStan diag_e is 1.06x–3.75x faster in wall time, because it avoids the overhead of BridgeStan’s C interface. A warm start can change the picture: starting weftmc.sample from fit_vi draws (starts=vi.draws[:4], warmup=250) puts loss_nl_log_corr 1.51x ahead of stan_diag (264.0 vs 175.1 ESS/s).

Severe funnels: every sampler fails. On the zero-variance bivariate phylogenetic funnel (phylo_mv, \(d = 408\)), all four samplers fail (\(\widehat{R} \ge 1.068\) or 330 divergences). The model has to be rewritten.

Code
disc_sub <- subset(disc, arm_key %in% c("weftmc", "stan_diag", "stan_dense", "stan_pathfinder"))

case_levels <- rev(c(
  "rbest_dmap_j2", "rbest_dmap_j3", "rbest_dmap_j4",
  "loss_nl_log_corr", "loss_nl_uncorr",
  "phylo_cov", "phylo_mv",
  "pm25_super_region", "pm25_cluster_log_region", "pm25_cluster_region",
  "pupil_fit4", "pupil_fit5", "park_rule"
))

disc_sub$case_id <- factor(disc_sub$case_id, levels = case_levels)
disc_sub$arm_clean <- factor(
  disc_sub$arm_key,
  levels = c("weftmc", "stan_diag", "stan_dense", "stan_pathfinder"),
  labels = c("WeftMC", "CmdStan diag_e", "CmdStan dense_e", "CmdStan PF + NUTS")
)
disc_sub$has_issue <- disc_sub$divergences > 0 | disc_sub$health_note != "ok"

p_rhat <- ggplot(disc_sub, aes(x = max_rhat, y = case_id, color = arm_clean, shape = has_issue)) +
  geom_vline(xintercept = 1.01, linetype = "dashed", color = blog_colors$text_light, linewidth = 0.5) +
  geom_vline(xintercept = 1.05, linetype = "dotted", color = blog_colors$text_light, linewidth = 0.5) +
  geom_point(size = 2.9, position = position_dodge(width = 0.55)) +
  scale_x_continuous(
    trans = "log10",
    breaks = c(1.0, 1.2, 1.5, 2.0, 3.0),
    labels = c("1.00", "1.20", "1.50", "2.00", "3.00")
  ) +
  scale_color_manual(values = c(blog_colors$teal, blog_colors$blue, blog_colors$red, blog_colors$purple)) +
  scale_shape_manual(
    values = c(`FALSE` = 16, `TRUE` = 4),
    labels = c(`FALSE` = "Clean", `TRUE` = "Divs / Flag")
  ) +
  labs(
    title = "Worst Parameter R-hat (13 Models)",
    subtitle = "Dashed = 1.01, dotted = 1.05",
    x = "Max rank-normalized R-hat (log scale)",
    y = NULL,
    color = NULL,
    shape = "Health:"
  ) +
  theme_blog(base_size = 10.5) +
  theme(legend.box = "vertical", legend.spacing.y = unit(2, "pt"), plot.margin = margin(12, 16, 12, 12))

p_divs <- ggplot(disc_sub, aes(x = divergences + 1, y = case_id, fill = arm_clean)) +
  geom_col(position = position_dodge(width = 0.72), width = 0.65, show.legend = FALSE) +
  scale_x_log10(
    breaks = c(1, 11, 101, 1001, 3001),
    labels = c("0", "10", "100", "1,000", "3,000")
  ) +
  scale_fill_manual(values = c(blog_colors$teal, blog_colors$blue, blog_colors$red, blog_colors$purple)) +
  labs(
    title = "Divergent Transitions (Count + 1)",
    subtitle = "0 divergences on all 13 WeftMC runs",
    x = "Divergent transitions (log10(count + 1) scale)",
    y = NULL
  ) +
  theme_blog(base_size = 10.5) +
  theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), plot.margin = margin(12, 12, 12, 12))

(p_rhat | p_divs) + plot_layout(guides = "collect") & theme(legend.position = "bottom")
Figure 3: Baseline (non-s2z) hierarchical and nonlinear benchmark across 13 models from Stan Discourse Topic 41542 (discourse-41542-results.csv). Left: worst rank-normalized \(\widehat{R}\) (stan_dense omitted on park_rule at \(d=2{,}442\)). Right: divergent transitions (0 across all 13 WeftMC runs; WeftMC flags warmup readiness on loss_nl_uncorr and phylo_mv).

3. Variational Inference and Structural Diagnostics

3.1 Score-Matching Stein–IV VI and the Reparameterization Advisor

Stan’s built-in variational methods either maximize the evidence lower bound (ELBO) by stochastic gradients (ADVI) (Kucukelbir et al. 2017) or build low-rank inverse-Hessian secants along an L-BFGS trajectory (Pathfinder) (Zhang et al. 2022). Recent score-based methods instead fit a Gaussian approximation from the target’s score \(s_\pi(x) = \nabla_x \log\pi(x)\), the gradient of its log density. They include GSM-VI (Modi et al. 2023), BaM (Cai et al. 2024), and Fisher-divergence HMC warmup (Seyboldt et al. 2026). fit_vi is a score-based method built on Stein’s identity with an instrumental variable (IV).

Let the current approximation have location \(m\) and scale factor \(B_0\), so that a draw is \(m + B_0 u\) with \(u\) standard normal. WeftMC stores \(B_0\) in low-rank-plus-diagonal form,

\[ B_0 = \operatorname{diag}(s)\big(I_d + Q \operatorname{diag}(\beta - \mathbf{1}_r) Q^\top\big), \]

which stretches the \(r\) orthonormal directions in the columns of \(Q\) by the factors \(\beta\), leaves their complement alone, and rescales each coordinate by \(s\). Each standard normal probe is split into an instrument \(z \sim \mathcal{N}(0, I_d)\) and independent noise \(\varepsilon \sim \mathcal{N}(0, I_d)\),

\[ u = \alpha z + \sqrt{1 - \alpha^2}\,\varepsilon, \qquad \alpha = 0.8, \]

so that \(u\) is standard normal and \(\mathbb{E}[z u^\top] = \alpha I_d\). Stein’s identity (Stein 1981; Opper and Archambeau 2009) states that \(\mathbb{E}[z\,h(z)^\top] = \mathbb{E}[J_h(z)]^\top\) for standard normal \(z\) and a smooth map \(h\) with Jacobian \(J_h\). Apply it to the whitened score \(h(z) = B_0^\top s_\pi(m + B_0 u)\), whose Jacobian in \(z\) is \(\alpha\, B_0^\top \nabla^2 \log\pi(m + B_0 u)\, B_0\):

\[ -\frac{1}{\alpha}\mathbb{E}\!\left[z\, \big(B_0^\top s_\pi(m + B_0 u)\big)^\top\right] = \mathbb{E}\!\left[B_0^\top \big(-\nabla^2 \log\pi(m + B_0 u)\big) B_0\right]. \]

The right side is the negative Hessian of the log target, averaged over the approximation and expressed in whitened coordinates. For a Gaussian target \(\pi = \mathcal{N}(\mu_\pi, \Sigma_\pi)\) the Hessian is constant and the right side is exactly \(B_0^\top \Sigma_\pi^{-1} B_0\), which is the identity precisely when \(B_0 B_0^\top = \Sigma_\pi\).

Why split \(u\) into \(z\) and \(\varepsilon\) instead of taking plain Stein (\(\alpha = 1\), \(z = u\))? On a single pass of \(K \ll d\) antithetic probe pairs across lock-free BridgeStan instances (stein_vi.hpp), WeftMC extracts the top sample eigenvectors \(Q_k \subset \mathbb{R}^K\) of the score-residual Gram matrix \(Y - \Lambda U\) (\(Y_k = -\tfrac{1}{2}[h(+u_k) - h(-u_k)]\)) and re-estimates each coordinate’s residual diagonal precision on the orthogonal complement \(\Pi_\perp = I_K - Q_k Q_k^\top\) via \(\hat{\lambda}_j = (z_j^\top \Pi_\perp y_j) / (z_j^\top \Pi_\perp u_j)\). Because \(Q_k\) is chosen from the largest sample residuals of \(U\) itself, \(\Pi_\perp\) depends on \(U\); setting \(z = u\) biases the residual diagonal precision downward on the selected coordinates. Retaining an independent \(\sqrt{1 - \alpha^2}\,\varepsilon\) component in \(U\) instruments \(U\) with \(Z\) on the same \(K\) probes without spending a second batch of gradient evaluations.

Once \(B_0\) is fitted, the marginal and conditional standard deviations of every coordinate have exact closed forms that cost \(O(d \cdot r)\), because the inverse of an identity-plus-low-rank matrix is again identity-plus-low-rank. The marginal \(\sigma_{\mathrm{marg}, j}\) is the spread of coordinate \(j\) on its own. The conditional \(\sigma_{\mathrm{cond}, j}\) is its spread with every other coordinate held fixed. They yield two structural diagnostics, one for every coordinate \(j\) and one for every random-effect block \(g\):

\[ \rho_j = \frac{\sigma_{\mathrm{marg}, j}}{\sigma_{\mathrm{cond}, j}} = \frac{1}{\sqrt{1 - R_{j \mid -j}^2}} \ge 1, \qquad \lambda_g = \operatorname{clip}\!\left(1 - \operatorname{median}_{i \in g}\!\big(\sigma_{\mathrm{cond}, i}^2\big),\; 0,\; 1\right). \]

The ridge ratio \(\rho_j\). \(R_{j \mid -j}^2\) is the share of the variance of coordinate \(j\) explained by a linear regression on all the others, so \(\rho_j^2\) is the variance inflation factor of regression diagnostics: 1 for a coordinate uncorrelated with the rest, large for one on a ridge. The translation ridge of Section 2.1 is the main case. Whenever an intercept \(\alpha\) can shift against a group vector \(z_g\) (\(\eta_n = \alpha + \tau z_{g[n]}\)), conditioning on \(z_g\) pins \(\alpha\) to \(O(N^{-1/2})\), while its marginal spread keeps a term that does not shrink with \(N\). Under a flat prior on \(\alpha\) in the balanced normal model with residual standard deviation \(\sigma\), \(J\) groups, and \(n = N/J\) observations per group, the conditional variance of \(\alpha\) is \(\sigma^2/N\) and its marginal variance is \(\sigma^2/N + \tau^2/J\), so \(\rho_\alpha^2 = 1 + n\tau^2/\sigma^2\). The advisor flags an anchor, the coordinate a group vector can shift against, when its \(\rho\) exceeds 4.

The centering weight \(\lambda_g\). A block of standardized group effects has a \(\mathcal{N}(0, 1)\) prior, so \(1 - \sigma_{\mathrm{cond}}^2\) is the share of its prior variance that the data remove. In the normal model the conditional precision of \(z_j\) is \(1 + n_j\tau^2/\sigma^2\), which gives \(1 - \sigma_{\mathrm{cond}, j}^2 = \tau^2/(\tau^2 + \sigma^2/n_j)\), the usual partial-pooling weight on a group’s own data. \(\lambda_g\) equals one minus the non-centering Fisher weight from Post 13. A value \(\lambda_g < 0.20\) favors non-centering, \(0.20 \le \lambda_g \le 0.80\) favors partial centering, and \(\lambda_g > 0.80\) favors centered sum_to_zero_vector contrasts (Bürkner 2017; Pinkney 2024).

These two diagnostics are the core of the Reparameterization Advisor, whose reports appear in the examples below.

Example: WHO air pollution (pm25_cluster_region, \(N = 6{,}003\), \(d = 18\)). Four-chain HMC on this model takes 17 minutes. Before spending them, run

weftmc vi pm25_cluster_region_model.so --data data.json --threads 4 --insights

It finishes in 0.22 s, 4.4x faster than 4-thread CmdStan Pathfinder, and reports two things. First, Intercept (\(\rho = 24.0\)) and slope b.1 (\(\rho = 10.9\)) are coupled to the 6-region random-effect vectors z_1.1 and z_1.2 along a ridge multiplier of 87.2. Second, \(\lambda_g = 1.000\), with the advice Use centered parameterization + sum_to_zero_vector. Taking the advice in two steps:

  1. Switching z_1 to sum_to_zero_vector, Stan’s type for a vector constrained to sum to zero, removes the translation direction by construction. Flagged ridges drop to 0 (444.6 s of HMC).
  2. Also centering onto the physical predictor scale, as \(\lambda_g = 1.000\) recommends, collapses the sd_1 Max rho from 19.9 to 1.2, lowers PSIS \(\hat{k}\) from 1.31 to 0.38, and cuts 4-chain weftmc.sample from 1,045.7 s (0.26 ESS/s) to 59.4 s (26.7 ESS/s), a 17.6x wall-time speedup.

Across four paired baseline and sum-to-zero multilevel models (\(N = 55\) to \(51{,}953\), \(d = 16\) to \(2{,}442\); Figure 4), weftmc.diagnose() flags all 13 baseline translation ridges (\(\rho_{\mathrm{anchor}} \in [8.8, 52.0]\)), reports 0 s2z findings after the switch to sum_to_zero_vector, and runs 1.4x–10.1x faster than 4-thread CmdStan Pathfinder.

Code
s2z <- read.csv("s2z-vi-advisor.csv", stringsAsFactors = FALSE, na.strings = "NA")
s2z$model_label <- factor(
  s2z$model_id,
  levels = c("loss_nl_log_corr", "pm25_cluster_region", "pupil_fit4", "park_rule"),
  labels = c("loss_nl\n(N=55, d=37)", "pm25_region\n(N=6k, d=18)", "pupil_fit4\n(N=2.2k, d=47)", "park_rule\n(N=52k, d=2,442)")
)
s2z$param_label <- factor(
  s2z$parameterization,
  levels = c("non_s2z", "s2z"),
  labels = c("Baseline (non-s2z)", "Sum-to-zero (s2z)")
)

p_rho <- ggplot(s2z, aes(x = model_label, y = anchor_rho, fill = param_label)) +
  geom_col(position = position_dodge(width = 0.7), width = 0.62) +
  geom_text(
    aes(label = paste0(num_s2z_ridges, " s2z")),
    position = position_dodge(width = 0.7),
    vjust = -0.45,
    size = 3.1,
    fontface = "bold",
    color = blog_colors$text
  ) +
  scale_y_continuous(limits = c(0, 59), breaks = seq(0, 50, 10)) +
  scale_fill_manual(values = c(blog_colors$red, blog_colors$teal)) +
  labs(
    title = "Advisor Ridge Count & Anchor Inflation",
    subtitle = "Labels show flagged s2z group translation ridges",
    x = NULL,
    y = "Anchor ridge ratio rho = sd_marg / sd_cond",
    fill = NULL
  ) +
  theme_blog(base_size = 10.5)

s2z_only <- subset(s2z, parameterization == "s2z")
time_long <- rbind(
  data.frame(model_label = s2z_only$model_label, method = "WeftMC VI (4t)", sec = s2z_only$vi_4t_sec),
  data.frame(model_label = s2z_only$model_label, method = "WeftMC VI (1t)", sec = s2z_only$vi_1t_sec),
  data.frame(model_label = s2z_only$model_label, method = "CmdStan PF (4t)", sec = s2z_only$cmdstan_pathfinder_4t_sec)
)
time_long <- subset(time_long, !is.na(sec))
time_long$method <- factor(
  time_long$method,
  levels = c("WeftMC VI (4t)", "WeftMC VI (1t)", "CmdStan PF (4t)")
)

p_vi_time <- ggplot(time_long, aes(x = model_label, y = sec, color = method, shape = method)) +
  geom_point(size = 3.3, position = position_dodge(width = 0.45)) +
  scale_y_log10(
    breaks = c(0.03, 0.1, 0.3, 1, 3, 10, 30),
    labels = c("0.03s", "0.1s", "0.3s", "1s", "3s", "10s", "30s")
  ) +
  scale_color_manual(values = c(blog_colors$teal, blog_colors$blue, blog_colors$purple)) +
  labs(
    title = "Variational Runtime on s2z Models",
    subtitle = "Log scale; CmdStan PF failed on pupil_fit4",
    x = NULL,
    y = "Wall-clock seconds (log scale)",
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 10.5)

p_rho | p_vi_time
Figure 4: Paired baseline (non_s2z) vs sum_to_zero_vector (s2z) evaluation (s2z-vi-advisor.csv). Left: flagged s2z translation ridge count above each bar and anchor variance-inflation ratio \(\rho_{\mathrm{anchor}}\) (on pupil_fit4, fixed-effect sigma ~ subj dummies keep \(\rho_{\mathrm{Intercept}}\) elevated after z_1 is zero-summed, while the z_1 ridges drop from 2 to 0). Right: 4-thread runtime of weftmc.fit_vi vs 1-thread weftmc.fit_vi and 4-thread CmdStan 2.40.0 Pathfinder (Pathfinder failed to initialize at init = 2.0 on pupil_fit4).

3.2 Scaling Standalone VI Without MCMC: SVRG-Stein and Panel WAIVES

Full-batch fit_vi evaluates all \(N\) rows at every L-BFGS step and every Stein probe. On large datasets (\(N = 40{,}000\), \(d = 250\)–\(700\)) that adds up: 2,485 passes over the data at \(d = 250\).

A cheap alternative reads the posterior covariance off the fluctuations of stochastic gradient descent (SGD) at a constant step size. Mandt, Hoffman, and Blei (Mandt et al. 2017) show that the stationary covariance \(\Sigma_\infty\) of the iterates solves

\[ P_w \Sigma_\infty + \Sigma_\infty P_w = \eta\, \Sigma_{\mathrm{SG}}, \]

where \(P_w\) is the posterior precision in the coordinates the chain runs in, \(\eta\) is the step size, and \(\Sigma_{\mathrm{SG}}\) is the covariance of the mini-batch gradient noise. The solution depends on the noise as much as on the curvature, and it diverges from \(P_w^{-1}\) whenever heavy-tailed row leverage makes \(\Sigma_{\mathrm{SG}} \ne P_w\).

MiniBatchTarget brings standalone VI down to 10–21 passes, with no MCMC, by combining three pieces.

Per-block StableAdamW warm start and DANE polish (optimizer="stable_adamw"). Outlier mini-batch gradients in one parameter block can destabilize the step sizes in another. StableAdamW (Wortsman et al. 2023) is AdamW with the update clipping of Adafactor: it shrinks the learning rate when the root mean square (RMS) of the gradient, divided by the square root of its running second-moment estimate, exceeds one. MiniBatchTarget applies that clip separately within each parameter block \(G\),

\[ \eta_{\mathrm{eff}, t, G} = \frac{\eta_t}{\max(1, \mathrm{RMS}_{t, G})}, \]

so an outlier throttles only its own block. Weight decay is cosine-annealed to zero by three-quarters of the way through the warm start, so tail iterate averaging targets the unregularized posterior. After the Stein covariance is fitted, if the whitened full-score norm still exceeds \(0.35\sqrt{d}\), a short variance-reduced L-BFGS polish in the style of DANE (Shamir et al. 2014) refines the mode in whitened coordinates. In those coordinates the score norm is the distance to the mode in posterior standard deviations, so the threshold is an RMS offset of 0.35 standard deviations per coordinate.

Multi-chain Panel WAIVES (method="waives", chains=8..16). Near the mode, preconditioned SGD iterates approximately follow a linear stochastic differential equation (SDE) whose drift matrix is \(-P_w\). Estimating that drift gives the precision with no reference to \(\Sigma_{\mathrm{SG}}\). WAIVES (Weak-form Asymptotically-unbiased Instrumental-Variable Estimation for SDEs) (Ruzayqat et al. 2026) is an estimator for exactly this problem. Weak form (Messenger and Bortz 2021) means the trajectory is never differentiated: the SDE is integrated against smooth bump functions \(\phi_p(t)\), which turns it into a linear regression among trajectory integrals. Least squares on that regression is biased, because the Brownian path that drives the response also enters the regressors, so regressor and error are correlated. The remedy is an instrument: a variable correlated with the regressor but independent of the error. WAIVES uses the trajectory integrated over a preceding, disjoint window, \(Z_k = \int_{I'_k} \psi_k(t) X_t\,\mathrm{d}t\). The process has memory, so \(Z_k\) predicts the regressor, and Brownian increments on disjoint windows are independent, so the within-window noise cancels. The Cragg–Donald \(F\) statistic (Cragg and Donald 1993; Staiger and Stock 1997) checks that the instrument is relevant, that is, strong enough to trust.

WeftMC runs \(C \in \{8, 16\}\) short preconditioned SGD chains from dispersed antithetic starts around \(m_0\). That turns the single-chain time-series IV into a panel IV with short \(T\) and large \(C\), which estimates \(-P_w\) directly. The instrument is what makes it work. Dropping the disjoint-window instrument on the same 8-chain trajectories (Panel Weak-Form OLS, for ordinary least squares) inflates the marginal standard deviation (SD) error from 22.6%–24.4% to 295.6%–313.4% and raises the Kullback–Leibler divergence \(\mathrm{KL}(q \,\|\, \pi_{\mathrm{ref}})\) by 97x–102x.

Cross-fitted SVRG-Stein (method="svrg", default). SVRG (Johnson and Zhang 2013), the stochastic variance-reduced gradient, corrects a mini-batch score with a full-data anchor: \(\hat{s}_{\mathrm{SVRG}}(x, B) = \hat{s}_B(x) - \hat{s}_B(m_{\mathrm{anc}}) + s(m_{\mathrm{anc}})\), where \(\hat{s}_B\) is the score estimated from batch \(B\) and \(s\) is the full-data score. With antithetic probes, the Stein estimate depends on the scores only through the difference between the two points of a pair, \(m_{\mathrm{anc}} \pm \delta\) with \(\delta = B_0 u_k\). When batch indices can be replayed, both points are evaluated on a shared mini-batch \(B_k\), and the anchor terms cancel:

\[ \hat{s}_{\mathrm{SVRG}}(m_{\mathrm{anc}} + \delta, B_k) - \hat{s}_{\mathrm{SVRG}}(m_{\mathrm{anc}} - \delta, B_k) = \hat{s}_{B_k}(m_{\mathrm{anc}} + \delta) - \hat{s}_{B_k}(m_{\mathrm{anc}} - \delta). \]

The zero-order batch noise, the part of the batch’s score error that does not depend on position, cancels in the same difference. Here SVRG-Stein splits its mini-batch probes into Fold 1 (subspace discovery) and Fold 2 (out-of-sample precision within the subspace), which eliminates in-sample subspace selection bias in \(O(d \cdot r)\) time:

from weftmc import MiniBatchTarget, fit_vi

mb = MiniBatchTarget(
    minibatch_logp_grad,
    batched_minibatch_fn=batched_logp_grad,
    dimension=d,
    num_obs=40_000,
    batch_size=250,
)
vi_svrg = fit_vi(mb, epochs=20.0, rank=20, method="svrg", optimizer="stable_adamw", seed=2026)
vi_panel = fit_vi(mb, epochs=10.0, rank=20, method="waives", chains=8, optimizer="stable_adamw", seed=2026)

I tested these estimators on a clustered binomial-logistic model with \(N = 40{,}000\) rows: \(10\) collinear fixed effects coupled to \(J \in \{240, 690\}\) group intercepts (\(d = 250\) and \(700\)), with Student-\(t_{3.5}\) covariate leverage so that \(\Sigma_{\mathrm{SG}} \ne H\) (Figure 5 and Table 2). The reference \(\pi_{\mathrm{ref}}\) is the exact full-data Laplace approximation.

Code
lsvi <- read.csv("large-scale-vi.csv", stringsAsFactors = FALSE, na.strings = "NA")
lsvi$dim_label <- factor(
  lsvi$dimension,
  levels = c(250, 700),
  labels = c("N = 40,000, d = 250 (r = 16)", "N = 40,000, d = 700 (r = 20)")
)
lsvi$method_short <- factor(
  lsvi$method,
  levels = c(
    "Mandt-Hoffman-Blei SGD Cov",
    "Panel Weak-Form OLS (No IV)",
    "Stochastic Low-Rank ADVI",
    "WeftMC MiniBatch (WAIVES, 1ch)",
    "WeftMC Panel WAIVES (8ch)",
    "WeftMC Panel WAIVES (16ch)",
    "WeftMC MiniBatch (SVRG-Stein)",
    "WeftMC Full-Batch VI"
  ),
  labels = c(
    "MHB SGD Cov (20 ep)",
    "Panel OLS, No IV (8.5 ep)",
    "Low-Rank ADVI (20 ep)",
    "WAIVES 1ch (20 ep)",
    "Panel WAIVES 8ch (10 ep)",
    "Panel WAIVES 16ch (16 ep)",
    "SVRG-Stein (21 ep)",
    "Full-Batch VI (2,485 ep)"
  )
)

p_lskl <- ggplot(lsvi, aes(x = kl_to_ref, y = method_short, color = dim_label, shape = dim_label)) +
  geom_point(size = 3.1, position = position_dodge(width = 0.45)) +
  scale_x_log10(
    breaks = c(0.1, 1, 10, 100, 1000, 10000),
    labels = c("0.1", "1", "10", "100", "1k", "10k")
  ) +
  scale_color_manual(values = c(blog_colors$teal, blog_colors$purple)) +
  guides(color = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  labs(
    title = "Posterior Divergence KL(q || pi_ref)",
    subtitle = "Lower is better (log scale)",
    x = "KL divergence to full-data posterior reference",
    y = NULL,
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 10.2) +
  theme(legend.position = "bottom")

mb_sub <- subset(
  lsvi,
  !(method %in% c("Mandt-Hoffman-Blei SGD Cov", "Panel Weak-Form OLS (No IV)"))
)
p_lssd <- ggplot(mb_sub, aes(x = wall_s, y = sd_rel_err * 100, color = method_short, shape = dim_label)) +
  geom_point(size = 3.2) +
  scale_x_log10(
    breaks = c(0.04, 0.1, 0.2, 0.5, 1, 3),
    labels = c("0.04s", "0.1s", "0.2s", "0.5s", "1s", "3s")
  ) +
  scale_color_manual(values = c(
    "Low-Rank ADVI (20 ep)" = blog_colors$red,
    "WAIVES 1ch (20 ep)" = blog_colors$gold,
    "Panel WAIVES 8ch (10 ep)" = blog_colors$purple,
    "Panel WAIVES 16ch (16 ep)" = blog_colors$navy,
    "SVRG-Stein (21 ep)" = blog_colors$teal,
    "Full-Batch VI (2,485 ep)" = blog_colors$blue
  )) +
  guides(color = guide_legend(ncol = 2), shape = "none") +
  labs(
    title = "Marginal SD Error vs Wall-Clock Time",
    subtitle = "Circle: d=250, Triangle: d=700 (>295% errors omitted)",
    x = "Wall-clock seconds (log scale)",
    y = "Relative marginal SD error (%)",
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 10.2) +
  theme(legend.position = "bottom")

p_lskl | p_lssd
Figure 5: Standalone VI at \(N = 40{,}000\) observations (\(d = 250\) and \(700\) clustered binomial-logistic models with Student-\(t_{3.5}\) leverage; large-scale-vi.csv). Left: Gaussian KL divergence \(\mathrm{KL}(q \,\|\, \pi_{\mathrm{ref}})\) to the exact full-data Laplace reference. Right: relative marginal SD error vs wall-clock seconds (omitting MHB SGD >940% and Panel OLS >295% errors).
Code
disp_ls <- data.frame(
  d = lsvi$dimension,
  Method = lsvi$method,
  Passes = sprintf("%.1f", lsvi$epochs),
  `Wall (s)` = sprintf("%.3f", lsvi$wall_s),
  `Mean RMSE` = sprintf("%.4f", lsvi$mean_rmse),
  `SD Rel Err` = sprintf("%.1f%%", 100 * lsvi$sd_rel_err),
  `Cov Rel Err` = sprintf("%.3f", lsvi$cov_rel_err),
  `KL to Ref` = sprintf("%.2f", lsvi$kl_to_ref),
  `Full PSIS k-hat` = ifelse(is.infinite(lsvi$k_hat), "inf", sprintf("%.2f", lsvi$k_hat)),
  `CD-F` = ifelse(is.na(lsvi$cd_f), "—", sprintf("%.1f", lsvi$cd_f)),
  check.names = FALSE
)

kable(disp_ls, row.names = FALSE, align = c("r", "l", "r", "r", "r", "r", "r", "r", "r", "r"))
Table 2: Standalone pure-VI benchmark at \(N = 40{,}000\) (large-scale-vi.csv; no MCMC). CD-F is the Cragg–Donald instrument strength for WAIVES.
d Method Passes Wall (s) Mean RMSE SD Rel Err Cov Rel Err KL to Ref Full PSIS k-hat CD-F
250 Stochastic Low-Rank ADVI 20.0 0.170 0.0270 34.4% 2.149 579.11 30.37 —
250 Mandt-Hoffman-Blei SGD Cov 20.0 0.086 0.0116 995.8% 164.613 14032.48 100.74 —
250 Panel Weak-Form OLS (No IV) 8.5 0.046 0.3644 313.4% 27.151 2143.74 120.76 —
250 WeftMC MiniBatch (WAIVES, 1ch) 20.0 0.154 0.0171 15.3% 0.315 15.87 1.91 38.6
250 WeftMC Panel WAIVES (8ch) 10.0 0.045 0.0143 22.6% 0.536 21.00 1.53 15.3
250 WeftMC Panel WAIVES (16ch) 16.0 0.066 0.0152 16.1% 0.623 21.91 1.76 119.9
250 WeftMC MiniBatch (SVRG-Stein) 21.0 0.081 0.0034 8.5% 0.304 4.50 0.72 —
250 WeftMC Full-Batch VI 2485.0 3.312 0.0030 0.2% 0.004 0.14 0.28 —
700 Stochastic Low-Rank ADVI 20.0 0.299 0.0462 49.5% 4.526 1569.65 78.67 —
700 Mandt-Hoffman-Blei SGD Cov 20.0 0.138 0.0264 940.3% 178.037 39202.01 inf —
700 Panel Weak-Form OLS (No IV) 8.5 0.079 0.6520 295.6% 28.315 5040.76 116.89 —
700 WeftMC MiniBatch (WAIVES, 1ch) 20.0 0.226 0.0473 19.7% 0.409 58.19 1.75 52.1
700 WeftMC Panel WAIVES (8ch) 10.0 0.079 0.0284 24.4% 0.536 51.91 4.42 9.5
700 WeftMC Panel WAIVES (16ch) 16.0 0.145 0.0168 17.1% 0.374 23.80 1.93 1.3
700 WeftMC MiniBatch (SVRG-Stein) 21.0 0.117 0.0196 18.9% 1.001 20.93 2.57 —

At \(d = 250\):

  • 10-pass Panel WAIVES (chains=8) finishes in 0.045 s at KL = 21.00. That is 74x faster than full-batch fit_vi and 3.8x faster than 20-epoch Low-Rank ADVI.
  • 21-pass SVRG-Stein reaches 8.5% marginal SD error and KL = 4.50 in 0.081 s.

At \(d = 700\):

  • 16-pass Panel WAIVES (chains=16) reaches 17.1% marginal SD error and 0.374 Frobenius covariance error (KL = 23.80) in 0.145 s.
  • 21-pass SVRG-Stein reaches KL = 20.93 in 0.117 s, against 1,569.7 for Low-Rank ADVI.

4. Case Study: Diagnosing and Reparameterizing ctsem State-Space Models

In Stan Discourse topic 41545, Charles Driver compared rstan, stanli, and the Julia engine of ctsem 4.0 (juliaFit / ContinuousTimeSEM.jl) across four continuous-time state-space models (Driver et al. 2017; Driver 2026). This section runs WeftMC on those four Stan programs in four steps: what the data-generating model simulates, what the Reparameterization Advisor prints on the unmodified ctsm.stan, how to change the Stan code in response, and how the resulting speed and parameter estimates compare with juliaFit and with the simulated truth.

4.1 Model, Simulated Data, and Two-Wave Identifiability

Driver’s models.R simulates \(S = 2{,}000\) subjects at \(T = 2\) time points (\(t_0 = 0\) and \(t_1 = 1\), so \(4{,}000\) rows). Each subject has \(p \in \{10, 20\}\) latent states \(\eta_s(t) \in \mathbb{R}^p\) that follow a linear SDE and are observed one-to-one through \(y_s(t_k) \in \mathbb{R}^p\):

\[ \mathrm{d}\eta_s(t) = A\,\eta_s(t)\,\mathrm{d}t + G\,\mathrm{d}W_s(t), \qquad y_s(t_k) = \eta_s(t_k) + \mu_{\mathrm{MM}, s} + \varepsilon_{s, k}. \]

Here \(A\) is the drift matrix (decay rates on the diagonal, cross-effects off it), \(Q = G G^\top\) is the diffusion covariance, \(\mu_{\mathrm{MM}, s}\) is a persistent subject-level intercept on the measurements with covariance \(\Sigma_{\mathrm{MM}}\), and \(\varepsilon_{s, k}\) is measurement noise with covariance \(\Sigma_\varepsilon\).

In make_data(p) the truth is simple: drift \(A = -I_p\), diffusion covariance \(Q = I_p\), zero measurement noise (\(\Sigma_\varepsilon = 0\)), zero intercepts, and no between-subject manifest random intercepts (\(\sigma_{\mathrm{MM}} = 0\)). The structure is in the initial state. Subjects \(1{:}1{,}000\) have the binary time-independent predictor \(x_s = \mathrm{TI1}_s = 0\) and initial covariance

\[ \Sigma_{T_0}^{(0)} = \left(\tfrac{1}{2}I_p + \mathbf{1}_p\mathbf{1}_p^\top\right)^2 = \tfrac{1}{4}I_p + (p + 1)\,\mathbf{1}_p\mathbf{1}_p^\top, \]

which is 11.25 on the diagonal and +11.00 off it at \(p = 10\) (21.25 and +21.00 at \(p = 20\)). Subjects \(1{,}001{:}2{,}000\) have \(x_s = 1\) and rows \(\lfloor p/2 \rfloor : p\) negated, which flips the cross-block initial covariances to \(-11.00\) (\(-21.00\)). Pooled over all \(2{,}000\) subjects, the cross-block off-diagonals of the initial covariance are therefore zero.

Four models are fitted, all with the random effects integrated out as extra states of an extended Kalman filter (intoverpop = "augmented"). d10 (\(d = 580\)) and d20 (\(d = 2{,}160\)) are linear. nl10 (\(d = 582\)) and nl20 (\(d = 2{,}162\)) replace the diagonal drift with the state-dependent \(A_{ii}(\eta) = -\log\!\big(1 + \exp(d_{\mathrm{self}, i} + d_{\mathrm{bylevel}}\,\eta_{(i \bmod p) + 1})\big)\), with true \(d_{\mathrm{bylevel}} = 0\). d10 and nl10 share the \(p = 10\) dataset, and d20 and nl20 share the \(p = 20\) dataset.

Two-wave identifiability. All four fitted models free a dense \(A\), a dense \(Q\), a diagonal \(\Sigma_\varepsilon\), random-effect scales on T0MEANS and MANIFESTMEANS (popsd), and TI1 slopes on every dynamic and mean parameter, while pooling \(\Sigma_{T_0}\) across TI1. That is more than two waves can separate. The pair \((y_{s,0}, y_{s,1})\) at \(\Delta t = 1\) supplies only three \(p \times p\) sample covariance blocks:

\[ \operatorname{Cov}(y_0) = \Sigma_{T_0} + \Sigma_{\mathrm{MM}} + \Sigma_\varepsilon, \qquad \operatorname{Cov}(y_1, y_0) = e^{A}\Sigma_{T_0} + \Sigma_{\mathrm{MM}}, \qquad \operatorname{Cov}(y_1) = e^{A}\Sigma_{T_0}e^{A^\top} + Q_{\Delta t = 1} + \Sigma_{\mathrm{MM}} + \Sigma_\varepsilon. \]

\(\operatorname{Cov}(y_0)\) sees only the sum of the three variance components, so variance can move out of \(\Sigma_{T_0}\) and into the persistent manifest intercepts \(\Sigma_{\mathrm{MM}}\) or the noise \(\Sigma_\varepsilon\) without changing it. A compensating change in the drift \(A\) then holds \(\operatorname{Cov}(y_1, y_0)\) nearly fixed, and the diffusion accumulated over the interval, \(Q_{\Delta t = 1}\), absorbs what is left in \(\operatorname{Cov}(y_1)\). The likelihood is nearly flat along this trade-off surface. Weakly informative priors (priors = TRUE) select where on it the posterior mode sits.

4.2 Step 1: Sharding ctsm.stan and Reading the Advisor Report

The first obstacle is the cost of one gradient. On a single core of the same Apple Silicon machine, a full 2,000-subject gradient takes 0.83–12.86 s in -O3 BridgeStan, against 0.144–1.339 s in Driver’s julia_side.R (0.036–0.273 s on 8 Julia threads).

The Stan program can be parallelized over subjects without editing it. intoverpop = "augmented" makes all unconstrained parameters global, so the log posterior is the log prior plus a sum of per-subject likelihood terms, and ctsm.stan already scales its prior by a data variable, real priormod (target += priormod * prior_lpdf(...)). Splitting the 2,000 subjects into \(K = 40\) stratified shards of 50 subjects, each its own JSON data file with priormod = 50 / 2000 = 0.025, therefore requires no Stan edits: the 40 shard log densities sum to the full log posterior with the prior counted exactly once. Summed across 8 threads, the 40 shards match the 2,000-subject gradient to 3.8e-15 relative error in 0.174–2.88 s. A single 50-subject shard runs in 21.4–288.9 ms, and each shard is a ready-made mini-batch.

Wrapping the 40 shards in MiniBatchTarget and running SVRG-Stein on the unmodified ctsm.stan,

vi = fit_vi(mb, method="svrg", epochs=15.0, rank=16, optimizer="stable_adamw", seed=2026)
print(vi.summary())

prints this report on d20 (\(d = 2{,}160\), 49.7 s):

PosteriorInsights (d=2160, rank=16, transport=affine, PSIS k_hat=0.000, ESS=100.0%)

Parameter Blocks:
  Block                 Size   Max rho   Med rho  Score res Shape           
  rawpopmeans            670      8.18      1.08   213.5331 skewed_or_funnel
  rawpopsdbase            40      6.48      1.07     4.8393 skewed_or_funnel
  sqrtpcov               780      1.02      1.00     4.0301 skewed_or_funnel
  tipredeffectparams     670      6.54      1.02   114.1815 skewed_or_funnel

Sum-to-Zero (s2z) Collinearity Ridges:
  - rawpopmeans (rho=8.18) <-> tipredeffectparams[670] (corr=-0.686, coherence=1.00, mult=2.24):
    Center covariate coupling between rawpopmeans and tipredeffectparams:
    reparameterize rawpopmeans = rawpopmeans_c - (0.04) * tipredeffectparams
    (or center predictor column by 0.04; max |corr|=0.69)

Partial-Centering Weights:
  - rawpopmeans[670]: lambda=0.922 -> centered_or_s2z_recommended (strong data precision, lambda=0.92)
  - rawpopsdbase[40]: lambda=1.000 -> centered_or_s2z_recommended (strong data precision, lambda=1.00)
  - sqrtpcov[780]: lambda=0.999 -> centered_or_s2z_recommended (strong data precision, lambda=1.00)
  - tipredeffectparams[670]: lambda=0.751 -> partial_centering_recommended (weight lambda=0.75)

Funnel Scale-Parent Couplings: none detected.

For each parameter block the report gives the largest and median ridge ratio \(\rho\), a whitened score residual (Score res), which is large where the fitted Gaussian explains the block’s score poorly, and a shape label. Two features of ctsm.stan explain everything in it (Figure 6).

An uncentered binary TI1 ridge (corr = -0.68 to -0.79). ctsm.stan constructs subject \(s\)’s unconstrained vector as \(\theta_{s, j} = \mu_{\mathrm{raw}, j} + \beta_{\mathrm{TI}, j} x_s\) with \(x_s \in \{0, 1\}\). Half the subjects constrain \(\mu_{\mathrm{raw}, j}\) alone and half constrain the sum \(\mu_{\mathrm{raw}, j} + \beta_{\mathrm{TI}, j}\). If each half contributes Fisher information \(\kappa\), the precision of the pair \((\mu_{\mathrm{raw}, j}, \beta_{\mathrm{TI}, j})\) and its inverse are

\[ \kappa\begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}, \qquad \kappa^{-1}\begin{pmatrix} 1 & -1 \\ -1 & 2 \end{pmatrix}, \]

a correlation of \(-1/\sqrt{2} \approx -0.707\). The advisor finds \(-0.678\) on nl10, \(-0.686\) on d20, and \(-0.790\) on nl20. Its suggested slope is too small, however (0.04–0.23). A rank-\(16\) factor spans at most \(16\) directions and there are \(670\) pairs, so the empirical slope is attenuated toward zero. The exact value needs no estimation. The covariance above implies \(\mu_{\mathrm{raw}, j} \approx \text{const} - \tfrac{1}{2}\beta_{\mathrm{TI}, j}\), and inspecting the TI1 column gives the exact sample mean \(\bar{x} = 0.50\). Centering the predictor removes the ridge.

A shifted log1p_exp variance origin. Funnel Scale-Parent Couplings: none detected confirms there is no funnel parent under the augmented filter, and \(\lambda_g \approx 1.00\) only reflects tight data precision (\(\sigma_{\mathrm{cond}} \approx 0.004\) on rawpopsdbase). The trouble is where the unconstrained origin lands. In ctsm.stan the positive DIFFUSION (\(s = 10\)) and MANIFESTVAR (\(s = 5\)) diagonals apply \(g(\theta) = s\log(1 + e^{2\theta})\). At a cold start \(\theta = 0\), the implied variance \(g(0)^2 = (s\log 2)^2\) puts DIFFUSIONcov at \(48.0\) (truth \(1.0\)) and MANIFESTcov at \(12.0\) (truth \(0.0\)), which buries z = 0 at lp(0) = -229,407 on d20.

Code
ell <- read.csv("ctsem-advisor-ellipse.csv", stringsAsFactors = FALSE)
ell$variant <- factor(
  ell$variant,
  levels = c("Baseline (ctsm.stan)", "Reparameterized (ctsm_reparam.stan)"),
  labels = c("Baseline ctsm.stan (r = -0.68)", "Reparameterized (r = +0.07)")
)

p_ell <- ggplot(ell, aes(x = x_std, y = y_std, color = variant, linetype = variant)) +
  geom_hline(yintercept = 0, color = blog_colors$grid, linewidth = 0.4) +
  geom_vline(xintercept = 0, color = blog_colors$grid, linewidth = 0.4) +
  geom_abline(slope = -1, intercept = 0, linetype = "dotted", color = blog_colors$text_light, linewidth = 0.45) +
  geom_path(linewidth = 1.05) +
  scale_x_continuous(limits = c(-2.45, 2.45), breaks = c(-2, -1, 0, 1, 2)) +
  scale_y_continuous(limits = c(-2.45, 2.45), breaks = c(-2, -1, 0, 1, 2)) +
  scale_color_manual(values = c(blog_colors$red, blog_colors$teal)) +
  scale_linetype_manual(values = c("solid", "solid")) +
  guides(color = guide_legend(nrow = 2), linetype = guide_legend(nrow = 2)) +
  labs(
    title = "1. Uncentered TI1 Ridge",
    subtitle = "90% contour on DRIFT[5,3] pair",
    x = "Intercept (std. units)",
    y = "TI1 slope (std. units)",
    color = NULL,
    linetype = NULL
  ) +
  theme_blog(base_size = 9.8) +
  theme(legend.position = "bottom")

th_grid <- seq(-1.7, 0.45, length.out = 250)
tform_df <- rbind(
  data.frame(theta = th_grid, var_val = (10 * log1p(exp(2 * th_grid)))^2, fam = "DIFFUSIONcov (scale = 10)"),
  data.frame(theta = th_grid, var_val = (5 * log1p(exp(2 * th_grid)))^2, fam = "MANIFESTcov (scale = 5)")
)
pts_init <- data.frame(
  theta = c(0, 0, -0.5 * log(10), -0.5 * log(5)),
  var_val = c((10 * log(2))^2, (5 * log(2))^2, (10 * log1p(1 / 10))^2, (5 * log1p(1 / 5))^2),
  state = factor(
    c("Baseline z=0", "Baseline z=0", "Shifted z=0", "Shifted z=0"),
    levels = c("Baseline z=0", "Shifted z=0")
  )
)

p_orig <- ggplot(tform_df, aes(x = theta, y = var_val, color = fam)) +
  geom_hline(yintercept = 1.0, linetype = "dotted", color = blog_colors$text_light, linewidth = 0.45) +
  geom_line(linewidth = 0.95) +
  geom_point(data = pts_init, aes(x = theta, y = var_val, shape = state), inherit.aes = FALSE, size = 3.0, color = blog_colors$text) +
  scale_y_log10(
    breaks = c(0.3, 1, 3, 10, 50),
    labels = c("0.3", "1", "3", "10", "50")
  ) +
  scale_color_manual(values = c(blog_colors$purple, blog_colors$blue)) +
  scale_shape_manual(values = c(4, 16)) +
  guides(color = guide_legend(nrow = 2), shape = guide_legend(nrow = 1)) +
  labs(
    title = "2. Variance Link Origin",
    subtitle = "Cold-start z = 0 drops from 12-48x to O(1)",
    x = "Unconstrained rawpopmeans coordinate",
    y = "Implied variance g(theta)^2 (log)",
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 9.8) +
  theme(legend.position = "bottom", legend.box = "vertical")

blk <- read.csv("ctsem-advisor-blocks.csv", stringsAsFactors = FALSE)
blk_pm <- subset(blk, block == "rawpopmeans")
blk_pm$model <- factor(blk_pm$model, levels = c("d10", "nl10", "d20", "nl20"))
blk_pm$var_short <- factor(
  blk_pm$variant,
  levels = c("Baseline (ctsm.stan)", "Reparameterized (ctsm_reparam.stan)"),
  labels = c("ctsm.stan (1 ridge)", "ctsm_reparam.stan (0 ridges)")
)

p_sres <- ggplot(blk_pm, aes(x = model, y = score_res, fill = var_short)) +
  geom_col(position = position_dodge(width = 0.76), width = 0.64) +
  geom_text(
    aes(label = sprintf("%.1fx", max_rho)),
    position = position_dodge(width = 0.76),
    vjust = -0.4,
    size = 2.8,
    fontface = "bold",
    color = blog_colors$text
  ) +
  scale_y_continuous(limits = c(0, 245), breaks = seq(0, 200, 50)) +
  scale_fill_manual(values = c(blog_colors$red, blog_colors$teal)) +
  guides(fill = guide_legend(nrow = 2)) +
  labs(
    title = "3. Advisor Score Residual",
    subtitle = "Bar labels: max ridge ratio rho",
    x = NULL,
    y = "Whitened score residual",
    fill = NULL
  ) +
  theme_blog(base_size = 9.8) +
  theme(legend.position = "bottom")

(p_ell | p_orig | p_sres) + plot_layout(widths = c(1, 1.05, 1.05))
Figure 6: Unconstrained geometry flagged by weftmc.diagnose() before and after ctsm_reparam.stan. Left: 90% conditional Gaussian contours (ctsem-advisor-ellipse.csv) for DRIFT[5, 3] intercept (rawpopmeans[49]) and TI1 slope (tipredeffectparams[49]) on nl10, rotating from \(r = -0.68\) to \(+0.07\) once TI1 is centered. Middle: ctsm.stan variance link \(v(\theta) = (s\log(1 + e^{2\theta}))^2\), showing how popmeans_shift = -log(s)/2 moves cold-start z = 0 from 48.0 and 12.0 to unit scale. Right: SVRG-Stein whitened score residual (ctsem-advisor-blocks.csv) and worst ridge ratio \(\rho_{\max}\) on rawpopmeans across all four models.

4.3 Step 2: Editing the Stan Program (ctsm_reparam.stan)

The tempting fix is to rescale each coordinate around zero to match \(\sigma_{\mathrm{cond}}\) (raw = 0.004 * z). Under a fixed-budget warm start that backfires: it pushes the unconstrained mode to \(\|z_*\| > 100\) and stalls d20 at lp = -125,142. Neither problem is a scale problem. ctsm_reparam.stan instead centers TI1 and shifts the origin of the log1p_exp variance links:

// 1. In transformed data: predictor column means & log1p_exp origin shift
vector[ntipred] tipred_colmeans = rep_vector(0.0, ntipred);
vector[nparams] popmeans_shift = rep_vector(0.0, nparams);
// ... tipred_colmeans[ci] = mean of non-missing tipredsdata[, ci] (= 0.50) ...
if (pr2 > 0 && matsetup[pr2, 4] == 1 && matvalues[pr2, 2] >= 2.0 && abs(matvalues[pr2, 3]) > 1e-8) {
  popmeans_shift[pi] = -log(matvalues[pr2, 2]) / matvalues[pr2, 3];
}

// 2. In parameters: replace rawpopmeans with rawpopmeans_c
vector[nparams] rawpopmeans_c;

// 3. In transformed parameters: reconstruct rawpopmeans (model block unchanged)
vector[nparams] rawpopmeans = popmeans_shift + rawpopmeans_c;
if (ntipred > 0 && ntieffects > 0) {
  rawpopmeans[tieffectindices[1:ntieffects]] -=
    TIPREDEFFECT[tieffectindices[1:ntieffects]] * tipred_colmeans;
}

The shift \(-\log(s)/2\) puts \(e^{2\theta} = 1/s\) at the origin, where \(g = s\log(1 + 1/s) \approx 1\). A cold start now implies variances of 0.91 and 0.83 where it implied 48.0 and 12.0.

The edit changes coordinates, not the model. The map \((\mu_{\mathrm{raw}, c}, \beta_{\mathrm{TI}}) \mapsto (c_{\mathrm{shift}} + \mu_{\mathrm{raw}, c} - \bar{x}\beta_{\mathrm{TI}}, \beta_{\mathrm{TI}})\) is unit upper-triangular, so \(\det J = 1\) and \(\log|\det J| = 0\): no Jacobian term is needed. Both compiled binaries agree to 0.00e+00 in log density, while lp(z = 0) rises by +20,914 to +35,246 nats before iteration 1. Re-running fit_vi drops the flagged ridges to 0 on all four models, lowers Max rho from 3.33–8.18 to 2.26–3.79, and cuts the rawpopmeans score residual on d20 from 213.5 to 26.3:

Parameter Blocks:
  Block                 Size   Max rho   Med rho  Score res Shape           
  rawpopmeans_c          670      3.42      1.06    26.2892 skewed_or_funnel
  rawpopsdbase            40      1.29      1.04     4.9180 skewed_or_funnel
  sqrtpcov               780      1.05      1.01     5.7835 skewed_or_funnel
  tipredeffectparams     670      3.79      1.06    27.6751 skewed_or_funnel

Sum-to-Zero (s2z) Collinearity Ridges: none detected (all anchor rho <= 4.0).

4.4 Step 3: Speed and Parameter Recovery vs juliaFit and Ground Truth

Code
ct <- read.csv("ctsem-comparison.csv", stringsAsFactors = FALSE, na.strings = c("NA", "nan", "NaN"))
model_levels <- c("nl20", "d20", "nl10", "d10")
model_labels <- c(
  "nl20 (20 nl, d=2,162)",
  "d20 (20 lin, d=2,160)",
  "nl10 (10 nl, d=582)",
  "d10 (10 lin, d=580)"
)
ct$model_label <- factor(ct$model, levels = model_levels, labels = model_labels)

grad_long <- rbind(
  data.frame(model_label = ct$model_label, engine = "BridgeStan -O3 (1t)", sec = ct$bridgestan_1t_grad_s),
  data.frame(model_label = ct$model_label, engine = "juliaFit EKF (1t, julia_side.R)", sec = ct$julia_1t_grad_s),
  data.frame(model_label = ct$model_label, engine = "WeftMC 8t sharded (Stan, exact)", sec = ct$weft_sharded_8t_grad_s),
  data.frame(model_label = ct$model_label, engine = "juliaFit EKF (8t)", sec = ct$julia_8t_grad_s),
  data.frame(model_label = ct$model_label, engine = "WeftMC 50-subj shard (Stan, 1t)", sec = ct$weft_shard50_grad_ms / 1000.0)
)
grad_long$engine <- factor(
  grad_long$engine,
  levels = c(
    "BridgeStan -O3 (1t)",
    "juliaFit EKF (1t, julia_side.R)",
    "WeftMC 8t sharded (Stan, exact)",
    "juliaFit EKF (8t)",
    "WeftMC 50-subj shard (Stan, 1t)"
  )
)

p_ct_grad <- ggplot(grad_long, aes(x = sec, y = model_label, color = engine, shape = engine)) +
  geom_point(size = 3.0, position = position_dodge(width = 0.55)) +
  scale_x_log10(
    breaks = c(0.02, 0.1, 0.5, 2, 10),
    labels = c("0.02s", "0.1s", "0.5s", "2s", "10s")
  ) +
  scale_color_manual(values = c(
    blog_colors$gold,
    blog_colors$blue,
    blog_colors$teal,
    blog_colors$purple,
    blog_colors$navy
  )) +
  guides(color = guide_legend(ncol = 2), shape = guide_legend(ncol = 2)) +
  labs(
    title = "Time per Gradient (Same Machine)",
    subtitle = "juliaFit leads per-pass; 50-subj shards run in 21-289ms",
    x = "Seconds per gradient (log scale)",
    y = NULL,
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 10.1) +
  theme(legend.position = "bottom")

vi_long <- rbind(
  data.frame(model_label = ct$model_label, method = "WeftMC WAIVES 8ch (ctsm.stan)", sec = ct$panel_waives_s, ok = TRUE),
  data.frame(model_label = ct$model_label, method = "WeftMC WAIVES 8ch (reparam)", sec = ct$reparam_waives_s, ok = TRUE),
  data.frame(model_label = ct$model_label, method = "WeftMC SVRG-Stein (ctsm.stan)", sec = ct$svrg_stein_s, ok = TRUE),
  data.frame(model_label = ct$model_label, method = "WeftMC SVRG-Stein (reparam)", sec = ct$reparam_svrg_s, ok = TRUE),
  data.frame(model_label = ct$model_label, method = "juliaFit MAP only (8t, no cov)", sec = ct$julia_map_8t_s, ok = TRUE),
  data.frame(model_label = ct$model_label, method = "juliaFit Full + Hessian (8t)", sec = ct$julia_full_8t_s, ok = ct$julia_full_ok == 1),
  data.frame(model_label = ct$model_label, method = "CmdStan 2.40 PF (4t)", sec = ct$cmdstan_pf_s, ok = ct$cmdstan_pf_ok == 1),
  data.frame(
    model_label = factor("d10", levels = model_levels, labels = model_labels),
    method = "WeftMC Full-Batch VI (4t)",
    sec = 323.81,
    ok = TRUE
  )
)
vi_long$method <- factor(
  vi_long$method,
  levels = c(
    "WeftMC WAIVES 8ch (ctsm.stan)",
    "WeftMC WAIVES 8ch (reparam)",
    "WeftMC SVRG-Stein (ctsm.stan)",
    "WeftMC SVRG-Stein (reparam)",
    "juliaFit MAP only (8t, no cov)",
    "juliaFit Full + Hessian (8t)",
    "CmdStan 2.40 PF (4t)",
    "WeftMC Full-Batch VI (4t)"
  )
)

p_ct_vi <- ggplot(vi_long, aes(x = sec, y = model_label, color = method, shape = ok)) +
  geom_point(size = 2.9, position = position_dodge(width = 0.66)) +
  scale_x_log10(
    breaks = c(5, 15, 50, 150, 350),
    labels = c("5s", "15s", "50s", "150s", "350s")
  ) +
  scale_color_manual(values = c(
    "WeftMC WAIVES 8ch (ctsm.stan)" = blog_colors$purple,
    "WeftMC WAIVES 8ch (reparam)" = "#22863a",
    "WeftMC SVRG-Stein (ctsm.stan)" = blog_colors$teal,
    "WeftMC SVRG-Stein (reparam)" = "#e36209",
    "juliaFit MAP only (8t, no cov)" = blog_colors$gold,
    "juliaFit Full + Hessian (8t)" = blog_colors$navy,
    "CmdStan 2.40 PF (4t)" = blog_colors$red,
    "WeftMC Full-Batch VI (4t)" = blog_colors$blue
  )) +
  scale_shape_manual(
    values = c(`TRUE` = 16, `FALSE` = 4),
    labels = c(`TRUE` = "Completed", `FALSE` = "Timeout (>210s)")
  ) +
  guides(color = guide_legend(ncol = 2), shape = guide_legend(ncol = 2)) +
  labs(
    title = "End-to-End Full Fit Time",
    subtitle = "d x d Hessian slows juliaFit full fit as d = 580 -> 2,162",
    x = "Total wall-clock seconds (log scale)",
    y = NULL,
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 10.1) +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    legend.position = "bottom",
    legend.box = "vertical"
  )

p_ct_grad | p_ct_vi
Figure 7: Apple Silicon benchmark across the four ctsem models (ctsem-comparison.csv; 2,000 subjects \(\times\) 2 waves). Left: time per gradient call. Right: end-to-end fit wall-clock time comparing WeftMC WAIVES 8ch and WeftMC SVRG-Stein (both ctsm.stan and ctsm_reparam.stan), 8-thread juliaFit MAP (estonly = TRUE, no covariance), 8-thread juliaFit L-BFGS + exact Hessian (estonly = FALSE), 4-thread CmdStan 2.40.0 Pathfinder, and 4-thread unsharded fit_vi on d10 (323.8 s); x marks timeouts above 210 s.
Code
disp_ct <- data.frame(
  Model = ct$model,
  d = formatC(ct$dimension, format = "d", big.mark = ","),
  `8t Grad (Weft/Julia)` = sprintf("%.3fs / %.3fs", ct$weft_sharded_8t_grad_s, ct$julia_8t_grad_s),
  `Julia MAP 8t (lp)` = sprintf("%.1fs (%.0f)", ct$julia_map_8t_s, ct$julia_map_8t_lp),
  `Julia Full+Hess 8t` = ifelse(
    ct$julia_full_ok == 1,
    sprintf("%.1fs (%.0f)", ct$julia_full_8t_s, ct$julia_full_8t_elbo),
    "Timeout >210s"
  ),
  `WAIVES 8ch (base)` = sprintf("%.1fs (%.0f)", ct$panel_waives_s, ct$panel_waives_elbo),
  `WAIVES 8ch (reparam)` = sprintf("%.1fs (%.0f)", ct$reparam_waives_s, ct$reparam_waives_elbo),
  `SVRG 8t (base)` = sprintf("%.1fs (%.0f)", ct$svrg_stein_s, ct$svrg_stein_elbo),
  `SVRG 8t (reparam)` = sprintf("%.1fs (%.0f)", ct$reparam_svrg_s, ct$reparam_svrg_elbo),
  `CmdStan PF 4t` = ifelse(
    ct$cmdstan_pf_ok == 1,
    sprintf("%.1fs (%.0f)", ct$cmdstan_pf_s, ct$cmdstan_pf_elbo),
    "Timeout >210s"
  ),
  check.names = FALSE
)

kable(disp_ct, row.names = FALSE, align = c("l", "r", "r", "r", "r", "r", "r", "r", "r", "r"))
Table 3: Gradient and full-fit comparison across the four ctsem models (ctsem-comparison.csv). Parentheses show (lp_mode) for MAP-only fits and (ELBO) for posterior approximations (Julia Full+Hess disables ctFit’s default coreset/Newton certification, which exceeds 990 s on d10).
Model d 8t Grad (Weft/Julia) Julia MAP 8t (lp) Julia Full+Hess 8t WAIVES 8ch (base) WAIVES 8ch (reparam) SVRG 8t (base) SVRG 8t (reparam) CmdStan PF 4t
d10 580 0.181s / 0.036s 10.5s (-45805) 56.6s (-71309) 4.8s (-48540) 5.5s (-47405) 6.9s (-46731) 7.3s (-47153) 164.9s (-55846)
nl10 582 0.174s / 0.055s 9.8s (-45755) 61.2s (-51307) 4.8s (-47345) 5.0s (-47412) 6.9s (-47089) 6.6s (-47229) 181.7s (-57610)
d20 2,160 2.876s / 0.155s 62.3s (-84496) Timeout >210s 43.9s (-90759) 50.9s (-90164) 49.7s (-93155) 61.9s (-89636) Timeout >210s
nl20 2,162 2.063s / 0.273s 48.5s (-85010) Timeout >210s 43.8s (-91534) 43.8s (-90697) 55.7s (-90816) 55.7s (-90065) Timeout >210s
Code
cf <- read.csv("ctsem-coord-fits.csv", stringsAsFactors = FALSE)
cf$model_lab <- factor(
  cf$model,
  levels = c("d10", "nl10"),
  labels = c("d10 (10 Linear Latents, true DRIFT[i,i] = -1.0)", "nl10 (10 State-Dependent Latents, true DRIFT[i,i] = -1.0)")
)
cf$method <- factor(
  cf$method,
  levels = c(
    "Weft SVRG (ctsm.stan)",
    "juliaFit (Full + Hessian)",
    "Weft SVRG (reparam)",
    "Weft WAIVES 8ch (reparam)"
  )
)

p_coord <- ggplot(cf, aes(x = factor(state), y = drift_mean, color = method, shape = method)) +
  geom_hline(yintercept = -1.0, linetype = "dashed", color = blog_colors$text, linewidth = 0.55) +
  geom_linerange(
    aes(ymin = drift_mean - 1.645 * drift_sd, ymax = drift_mean + 1.645 * drift_sd),
    position = position_dodge(width = 0.62),
    linewidth = 0.55,
    alpha = 0.85
  ) +
  geom_point(position = position_dodge(width = 0.62), size = 2.4) +
  facet_wrap(~ model_lab, ncol = 2, scales = "free_y") +
  scale_color_manual(values = c(
    "Weft SVRG (ctsm.stan)" = blog_colors$red,
    "juliaFit (Full + Hessian)" = blog_colors$navy,
    "Weft SVRG (reparam)" = "#e36209",
    "Weft WAIVES 8ch (reparam)" = "#22863a"
  )) +
  labs(
    title = "Coordinate-Level Drift Diagonal Recovery (Mean and 90% Interval)",
    subtitle = "Dashed line marks true data-generating DRIFT[i,i] = -1.00 across states i = 1..10",
    x = "Latent state index i",
    y = "Constrained pop_DRIFT[i, i]",
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 9.9) +
  theme(legend.position = "top")

tvf_all <- read.csv("ctsem-true-vs-fitted.csv", stringsAsFactors = FALSE)
keep_m <- c("True Simulated", "juliaFit", "Weft SVRG (ctsm.stan)", "Weft SVRG (reparam)", "Weft WAIVES (reparam)")
tvf_p <- subset(tvf_all, method %in% keep_m)

long_tvf <- rbind(
  data.frame(model = tvf_p$model, method = tvf_p$method, panel = "DRIFT diag (true = -1)", val = tvf_p$drift_diag_mean),
  data.frame(model = tvf_p$model, method = tvf_p$method, panel = "DIFFUSION diag (true = 1)", val = tvf_p$diff_diag_mean),
  data.frame(model = tvf_p$model, method = tvf_p$method, panel = "popsd_MM (true = 0)", val = tvf_p$popsd_mm_mean),
  data.frame(model = tvf_p$model, method = tvf_p$method, panel = "T0cov diag (true = 11.25 / 21.25)", val = tvf_p$t0_diag_mean)
)
long_tvf$model <- factor(long_tvf$model, levels = c("d10", "nl10", "d20", "nl20"))
long_tvf$panel <- factor(
  long_tvf$panel,
  levels = c(
    "DRIFT diag (true = -1)",
    "DIFFUSION diag (true = 1)",
    "popsd_MM (true = 0)",
    "T0cov diag (true = 11.25 / 21.25)"
  )
)

truth_pts <- subset(long_tvf, method == "True Simulated")
est_pts <- subset(long_tvf, method != "True Simulated")
est_pts$method <- factor(
  est_pts$method,
  levels = c("Weft SVRG (ctsm.stan)", "juliaFit", "Weft SVRG (reparam)", "Weft WAIVES (reparam)"),
  labels = c("Weft SVRG (ctsm.stan)", "juliaFit", "Weft SVRG (reparam)", "Weft WAIVES 8ch (reparam)")
)

p_blocks <- ggplot(est_pts, aes(x = model, y = val, color = method, shape = method)) +
  geom_point(position = position_dodge(width = 0.55), size = 2.7) +
  geom_point(
    data = truth_pts,
    aes(x = model, y = val),
    inherit.aes = FALSE,
    shape = 18,
    size = 3.6,
    color = blog_colors$text
  ) +
  facet_wrap(~ panel, ncol = 4, scales = "free_y") +
  scale_color_manual(values = c(
    "Weft SVRG (ctsm.stan)" = blog_colors$red,
    "juliaFit" = blog_colors$navy,
    "Weft SVRG (reparam)" = "#e36209",
    "Weft WAIVES 8ch (reparam)" = "#22863a"
  )) +
  labs(
    title = "Two-Wave Variance and Decay Trade-Off Across All Four Models",
    subtitle = "Black diamonds mark exact data-generating values from models.R",
    x = NULL,
    y = "Block mean",
    color = NULL,
    shape = NULL
  ) +
  theme_blog(base_size = 9.9) +
  theme(legend.position = "none")

p_coord / p_blocks + plot_layout(heights = c(1.15, 0.95))
Figure 8: Constrained parameter fits compared against juliaFit and the simulated truth (ctsem-coord-fits.csv and ctsem-true-vs-fitted.csv). Top: posterior means and central 90% intervals for the 10 diagonal drift rates \(A_{ii}\) on d10 and nl10 vs true -1.00 (dashed). Bottom: block means across all four models vs black diamonds marking true data-generating values.
Code
tvf <- read.csv("ctsem-true-vs-fitted.csv", stringsAsFactors = FALSE)
tvf_sub <- subset(tvf, method != "Weft WAIVES (ctsm.stan)")
disp_tvf <- data.frame(
  Model = tvf_sub$model,
  Source = tvf_sub$method,
  `DRIFT diag` = sprintf("%+.3f", tvf_sub$drift_diag_mean),
  `DRIFT off RMSE` = sprintf("%.3f", tvf_sub$drift_off_rmse),
  `DIFF diag` = sprintf("%.3f", tvf_sub$diff_diag_mean),
  `DIFF off RMSE` = sprintf("%.3f", tvf_sub$diff_off_rmse),
  `MANIF diag` = sprintf("%.3f", tvf_sub$manif_diag_mean),
  `T0 (diag / w / x)` = sprintf("%.2f / %.2f / %+.2f", tvf_sub$t0_diag_mean, tvf_sub$t0_within_off_mean, tvf_sub$t0_cross_off_mean),
  `T0M / MM RMSE` = sprintf("%.3f / %.3f", tvf_sub$t0means_rmse, tvf_sub$manifestmeans_rmse),
  `popsd_MM` = sprintf("%.3f", tvf_sub$popsd_mm_mean),
  check.names = FALSE
)

kable(disp_tvf, row.names = FALSE, align = c("l", "l", "r", "r", "r", "r", "r", "r", "r", "r"))
Table 4: Constrained parameter recovery against the data-generating values from models.R (ctsem-true-vs-fitted.csv).
Model Source DRIFT diag DRIFT off RMSE DIFF diag DIFF off RMSE MANIF diag T0 (diag / w / x) T0M / MM RMSE popsd_MM
d10 True Simulated -1.000 0.000 1.000 0.000 0.000 11.25 / 11.00 / +0.00 0.000 / 0.000 0.000
d10 juliaFit -0.367 0.139 0.314 0.022 0.137 8.23 / 7.47 / -0.37 0.164 / 0.144 0.631
d10 Weft SVRG (ctsm.stan) -5.288 0.471 0.262 0.045 0.105 3.64 / 3.24 / -0.06 0.086 / 0.055 1.206
d10 Weft SVRG (reparam) -1.164 0.444 0.176 0.048 0.170 4.12 / 3.64 / -0.05 0.083 / 0.065 1.300
d10 Weft WAIVES (reparam) -0.969 0.426 0.156 0.039 0.178 4.03 / 3.44 / -0.02 0.087 / 0.069 1.293
nl10 True Simulated -1.000 0.000 1.000 0.000 0.000 11.25 / 11.00 / +0.00 0.000 / 0.000 0.000
nl10 juliaFit -0.747 0.094 0.657 0.036 0.052 9.06 / 8.50 / -0.92 0.110 / 0.051 0.574
nl10 Weft SVRG (ctsm.stan) -1.642 0.364 0.295 0.088 0.139 3.90 / 3.45 / -0.00 0.087 / 0.055 1.225
nl10 Weft SVRG (reparam) -1.009 0.425 0.199 0.060 0.169 4.29 / 3.62 / +0.00 0.079 / 0.064 1.336
nl10 Weft WAIVES (reparam) -0.882 0.419 0.188 0.052 0.175 4.24 / 3.41 / +0.03 0.135 / 0.087 1.347
d20 True Simulated -1.000 0.000 1.000 0.000 0.000 21.25 / 21.00 / +0.00 0.000 / 0.000 0.000
d20 juliaFit -0.100 0.195 0.196 0.040 0.169 8.70 / 8.50 / +0.13 0.172 / 0.144 1.691
d20 Weft SVRG (ctsm.stan) -4.271 0.422 0.342 0.046 0.140 3.84 / 3.50 / -0.21 0.084 / 0.051 1.250
d20 Weft SVRG (reparam) -1.862 0.425 0.251 0.074 0.163 4.38 / 4.04 / +0.01 0.116 / 0.079 1.311
d20 Weft WAIVES (reparam) -1.834 0.422 0.246 0.079 0.166 4.11 / 3.75 / +0.01 0.129 / 0.095 1.278
nl20 True Simulated -1.000 0.000 1.000 0.000 0.000 21.25 / 21.00 / +0.00 0.000 / 0.000 0.000
nl20 juliaFit -0.748 0.089 0.622 0.028 0.073 12.74 / 12.40 / +0.69 0.156 / 0.084 1.462
nl20 Weft SVRG (ctsm.stan) -1.806 0.361 0.361 0.071 0.150 3.87 / 3.49 / -0.17 0.078 / 0.057 1.275
nl20 Weft SVRG (reparam) -1.088 0.463 0.288 0.115 0.175 4.49 / 3.96 / +0.02 0.092 / 0.064 1.357
nl20 Weft WAIVES (reparam) -1.038 0.461 0.266 0.108 0.186 4.17 / 3.62 / +0.01 0.101 / 0.088 1.322

Three results stand out across Figure 7, Figure 8, Table 3, and Table 4.

juliaFit wins per gradient and hits a wall at the \(O(d^2)\) Hessian. On 8 threads, juliaFit evaluates full gradients 3.2x–18.5x faster than sharded BridgeStan (0.036–0.273 s vs 0.174–2.88 s) and finds maximum a posteriori (MAP) point estimates fast (9.8–62.3 s at estonly = TRUE). Posterior uncertainty is another matter. Computing it through a dense \(d \times d\) Hessian (estonly = FALSE) raises total runtime by 46.0–51.5 s over MAP-only at \(d \approx 580\) (from 10.5 s to 56.6 s on d10, and from 9.8 s to 61.2 s on nl10) and times out past 210 s at \(d \approx 2{,}160\).

On ctsm_reparam.stan, WeftMC’s VI is faster end to end. WAIVES with 8 chains finishes in 5.0–5.5 s at 10 latents, 10x–12x faster than juliaFit with its Hessian, and in 43.8–50.9 s at 20 latents, faster than MAP-only juliaFit. It reaches ELBO = -47,405 and -47,412 at 10 latents and -90,164 and -90,697 at 20 latents. SVRG-Stein finishes in 6.6–7.3 s and 55.7–61.9 s. At 10 latents its mode lp(mu) is within 42–76 nats (0.07–0.13 nats per dimension) of the juliaFit MAP, and at 20 latents it reaches ELBO = -89,636 and -90,065.

Parameter recovery depends on where a fit lands on the two-wave surface. On the unmodified ctsm.stan, the uncentered TI1 and the log1p_exp offset make 16-pass VI overshoot the linear DRIFT diagonals: -5.29 on d10 and -4.27 on d20, against a simulated -1.000. On ctsm_reparam.stan, WAIVES 8ch and SVRG-Stein place them at -0.969 and -1.164 on d10, -0.882 and -1.009 on nl10, -1.834 and -1.862 on d20, and -1.038 and -1.088 on nl20. They also cut the pop_DRIFT root-mean-square error (RMSE) measured against juliaFit by 3.9x (d10) and 2.0x (d20), and they recover the 0.00 cross-block cancellation in T0cov (-0.05 to +0.03).

juliaFit does better on two blocks. It recovers more of the pooled T0cov diagonal (8.23–12.74, against a truth of 11.25 at \(p = 10\) and 21.25 at \(p = 20\)), and its off-diagonal DRIFT is tighter (RMSE 0.089–0.195 vs 0.419–0.463). It also puts persistent variance into popsd_MM (0.57–1.69, truth 0), and its linear DRIFT diagonals sit at -0.367 (d10) and -0.100 (d20). Both engines are choosing points on the flat surface of Section 4.1. Separating all five variance and decay blocks without relying on priors requires \(T \ge 3\) measurement waves per subject.

5. Nonlinear ODE Case Study: Diagnosing and Reparameterizing a Stan SIR Model

The linear and state-dependent ctsem models fail through uncentered predictor ridges spread across hundreds of Gaussian coordinates. Small nonlinear ODE models fail in a different way: log and logit parameter transforms interact with exponential forward dynamics and with initial conditions that sit on a boundary. Eric Novik’s Generable tutorial (Novik 2022), following Chatzilena et al. (2019), shows this on a three-parameter compartmental susceptible-infected-recovered (SIR) model (sir.stan and sir-pred.stan).

5.1 Model and Observation Regimes

A closed population of \(N = 763\) individuals is split into compartment fractions \((S, I, R)\). Starting at \(t_0 = 0\) from \(y_{\mathrm{init}} = (S_0, 1 - S_0, 0)\), sir.stan integrates

\[ \frac{\mathrm{d}S}{\mathrm{d}t} = -\beta S I, \qquad \frac{\mathrm{d}I}{\mathrm{d}t} = \beta S I - \gamma I, \qquad \frac{\mathrm{d}R}{\mathrm{d}t} = \gamma I, \]

with ode_rk45, where \(\beta\) is the transmission rate and \(\gamma\) the recovery rate. Observed infected counts are \(y_i \sim \operatorname{Poisson}(N\,I(t_i))\). The priors are theta ~ lognormal(0, 1) on \(\theta = \{\beta, \gamma\}\), declared real<lower=0>, and S0 ~ beta(1, 1), declared real<lower=0, upper=1>.

Novik’s sir.R (set.seed(1234)) simulates \(n = 100\) observation times across \(t \in [1, 15]\) with \(\beta = 2.0\), \(\gamma = 0.5\), and one infected individual at \(t = 1\) (\(I(1) = 1\)). The basic reproduction number is \(R_0 = \beta/\gamma = 4.0\), and the expected peak is \(N I = 308.0\) at day \(6.23\). Two regimes are fitted.

Full 15-day outbreak (\(n = 100\), days 1.0–15.0). The data cover the exponential rise, the peak depletion, and the post-peak recovery.

Pre-peak 5-day training with a 70-point forecast (\(n = 30\), days 1.0–5.1, forecasting \(n_{\mathrm{pred}} = 70\) points on days 5.2–15.0). The training window stops while infections are still climbing (\(y\) rises from 0 to 181). Here \(\beta\) and \(\gamma\) are nearly collinear, which led Novik to raise adapt_delta to 0.98 in CmdStan.

5.2 Step 1: Reading the Reparameterization Advisor Output

Running weftmc.fit_vi on the 5-day pre-peak dataset (sir-pred.stan, 4 threads) finishes in 52 ms and prints:

VariationalResult: d=3, draws=2000, threads=4, transport=low_rank, PSIS k_hat=5.009, ESS=0.1%, grad_calls=5419, wall=0.052s
---------------------------------------------------------------------------------------------------------------------------
PosteriorInsights (d=3, rank=3, transport=low_rank, PSIS k_hat=5.009, ESS=0.1%)

Parameter Blocks:
  Block                 Size   Max rho   Med rho  Score res Shape           
  theta                    2      1.24      1.14   326.4929 skewed_or_funnel
  S0                       1      1.25      1.25    98.8252 skewed_or_funnel

Sum-to-Zero (s2z) Collinearity Ridges: none detected (all anchor rho <= 4.0).

Partial-Centering Weights: no hierarchical blocks detected.

Funnel Scale-Parent Couplings: none detected.

Nonlinear Link & Boundary Couplings:
  - theta[1] <-> theta[2] (difference_rate_softplus): Parameterize net growth r = theta[1] - theta[2] = log1p_exp(u_r) and theta[2] = log1p_exp(u_gamma) so theta[1] = theta[2] + r decouples net growth from recovery/decay and avoids the double exponential exp(t * exp(z)) (net rate ~ 0.72; add target += log_inv_logit(u_r) + log_inv_logit(u_gamma)).
  - S0 <-> theta (boundary_lever_arm): S0 is pinned near upper bound 1 (z=+4.40, 96.2 SDs from z=0; 1 - S0 ~ 1.21e-02) and coupled to net growth r (corr=+0.944, implied t_ref - t0 = 3.08). Anchor complement log-odds at the count-weighted rising-phase time t_ref in transformed data and pull back to t0 via u_I0 = logit(i_ref) + z_I_ref - r * (t_ref - t0), S0 = 1 - inv_logit(u_I0) (add target += log_inv_logit(u_I0) + log1m_inv_logit(u_I0)).

The fit itself has failed, with PSIS \(\hat{k} = 5.009\) and 0.1% ESS, and the report says why. (On the 15-day dataset fit_vi does recover accurate posterior quantiles in 0.23 s, by PSIS importance resampling (PSIS-SIR) at \(\hat{k} = 0.706\) and 18.1% ESS. It emits the same two Nonlinear Link & Boundary Couplings warnings, with Score res = 2.49e7, z = +8.79, and an implied t_ref - t0 = 3.02.)

Neither finding requires touching ode_rk45. probe_stan_constraints evaluates param_constrain at four reference vectors (include_tp = False, 0.25 ms) and identifies theta[1] and theta[2] as exp_lower (the transform \(e^z\)) and S0 as logit_bounded on \([0, 1]\). The advisor then inspects the variational score residuals and the proposal covariance (Figure 9).

The growth-rate ridge and the double exponential (difference_rate_softplus). Before peak depletion, while \(S(t) \approx 1\), the infected fraction obeys \(\mathrm{d}I/\mathrm{d}t \approx (\beta - \gamma) I\), so expected counts follow \(\lambda(t) \approx N I_0 e^{r t}\) with net growth rate \(r = \beta - \gamma\). Pre-peak data see \(\beta\) and \(\gamma\) almost only through their difference. The 5-day data pin \(r = 1.49 \pm 0.07\) and leave \(\gamma = 0.50 \pm 0.17\) wide, which induces \(\operatorname{Corr}(\beta, \gamma) = 0.987\) in MCMC. In the unconstrained log-rate coordinates the ridge is the curve \(e^{z_1} - e^{z_2} = r\), which is bent, so no linear map straightens it. There is a second problem. Under <lower=0> a rate is the exponential of its coordinate, so declaring \(r\) itself that way would set \(r = e^{z_r}\) and make \(\lambda(t) \propto \exp(t e^{z_r})\) doubly exponential in \(z_r\). The advisor therefore recommends the softplus link log1p_exp, \(r = \log(1 + e^{u_r})\), which is positive but grows only linearly.

The boundary origin trap and the rising-phase lever arm (boundary_lever_arm). real<lower=0, upper=1> S0 puts the unconstrained origin z = 0 at \(S_0 = 0.50\), that is, \(381.5\) infected students at \(t = 0\). The posterior is over \(8\) logit units away, at \(\operatorname{logit}(S_0) = +8.13\) (\(S_0 = 0.99970\)). On n = 30, L-BFGS stalls halfway at \(+4.40\) (\(\beta = 0.85\), \(\gamma = 0.03\)), which PSIS k_hat = 5.009 catches immediately.

The coupling of \(S_0\) to \(r\) is a lever arm. Write \(u_{I_0} = \operatorname{logit}(1 - S_0)\) for the initial log-odds of infection. During the rise, \(\log\lambda(t) \approx u_{I_0} + r(t - t_0)\) up to a constant: a straight line in \(t\) with intercept \(u_{I_0}\) at \(t_0\) and slope \(r\). The line is observed over \(t \in [1.0, 5.1]\) (mean \(\bar{t} = 3.05\)), not at \(t_0 = 0\), so the intercept is an extrapolation, and an error in the slope moves it by \(-(\bar{t} - t_0)\) times as much. The advisor’s regression slope \(-\operatorname{Cov}(u_{I_0}, r)/\operatorname{Var}(r) = 3.08\) recovers that lever arm directly from the proposal covariance. This is the uncentered predictor ridge of Section 4.2 again, with time as the predictor, and the cure is the same: put the intercept where the data are.

Code
sir_dr <- read.csv("sir-posterior-draws.csv", stringsAsFactors = FALSE, na.strings = "NA")
sir_clouds <- subset(sir_dr, source != "Baseline VI Stall (sir.stan, k_hat=5.01)")
sir_stall <- subset(sir_dr, source == "Baseline VI Stall (sir.stan, k_hat=5.01)")
sir_clouds$source <- factor(
  sir_clouds$source,
  levels = c("Exact MCMC Posterior", "WeftMC VI (sir_reparam.stan, 0.18s)")
)

p_sir_bg <- ggplot(sir_clouds, aes(x = gamma, y = beta, color = source)) +
  geom_abline(slope = 1, intercept = 1.5, linetype = "dotted", color = blog_colors$text_light, linewidth = 0.5) +
  geom_point(alpha = 0.42, size = 1.35) +
  geom_point(
    data = sir_stall,
    aes(x = gamma, y = beta),
    inherit.aes = FALSE,
    shape = 4,
    stroke = 1.2,
    size = 3.3,
    color = blog_colors$red
  ) +
  annotate("point", x = 0.5, y = 2.0, shape = 18, size = 3.6, color = blog_colors$text) +
  annotate("text", x = 0.13, y = 0.98, label = "Baseline VI\n(k_hat = 5.01)", size = 2.8, color = blog_colors$red, hjust = 0) +
  scale_color_manual(values = c(blog_colors$navy, blog_colors$teal)) +
  guides(color = guide_legend(nrow = 2)) +
  labs(
    title = "1. Pre-Peak Growth Ridge",
    subtitle = "Corr(beta, gamma) = 0.987 along beta - gamma = 1.5",
    x = "Recovery rate gamma",
    y = "Transmission rate beta",
    color = NULL
  ) +
  theme_blog(base_size = 9.8) +
  theme(legend.position = "bottom")

p_sir_lev <- ggplot(sir_clouds, aes(x = r, y = logit_S0, color = source)) +
  geom_point(alpha = 0.42, size = 1.35) +
  geom_point(
    data = sir_stall,
    aes(x = r, y = logit_S0),
    inherit.aes = FALSE,
    shape = 4,
    stroke = 1.2,
    size = 3.3,
    color = blog_colors$red
  ) +
  annotate("text", x = 0.90, y = 5.42, label = "Stalled from z = 0\n(mode z = +4.40)", size = 2.8, color = blog_colors$red, hjust = 0) +
  scale_y_continuous(limits = c(4.9, 9.5), breaks = 5:9) +
  scale_color_manual(values = c(blog_colors$navy, blog_colors$teal)) +
  labs(
    title = "2. Boundary & Lever Arm",
    subtitle = "Origin z = 0 starts at 381.5 infected",
    x = "Net growth rate r = beta - gamma",
    y = "logit(S0)",
    color = NULL
  ) +
  theme_blog(base_size = 9.8) +
  theme(legend.position = "none")

sir_rib <- read.csv("sir-forecast-ribbons.csv", stringsAsFactors = FALSE)
rib_long <- rbind(
  data.frame(day = sir_rib$day, model = "Exact MCMC (3.28s)", q05 = sir_rib$mc_q05, q50 = sir_rib$mc_q50, q95 = sir_rib$mc_q95),
  data.frame(day = sir_rib$day, model = "WeftMC VI reparam (0.18s)", q05 = sir_rib$vi_rep_q05, q50 = sir_rib$vi_rep_q50, q95 = sir_rib$vi_rep_q95)
)
rib_long$model <- factor(rib_long$model, levels = c("Exact MCMC (3.28s)", "WeftMC VI reparam (0.18s)"))

p_sir_fc <- ggplot() +
  geom_ribbon(
    data = rib_long,
    aes(x = day, ymin = q05, ymax = q95, fill = model),
    alpha = 0.22
  ) +
  geom_line(
    data = rib_long,
    aes(x = day, y = q50, color = model, linetype = model),
    linewidth = 0.9
  ) +
  geom_vline(xintercept = 5.10, linetype = "dashed", color = blog_colors$text_light, linewidth = 0.5) +
  geom_point(
    data = sir_rib,
    aes(x = day, y = y_obs, shape = split),
    size = 1.45,
    color = blog_colors$text
  ) +
  scale_color_manual(values = c(blog_colors$navy, blog_colors$teal)) +
  scale_fill_manual(values = c(blog_colors$navy, blog_colors$teal)) +
  scale_linetype_manual(values = c("solid", "dashed")) +
  scale_shape_manual(values = c("Forecast (days 5.2-15)" = 1, "Train (days 1-5.1)" = 16)) +
  guides(
    color = guide_legend(nrow = 2),
    fill = guide_legend(nrow = 2),
    linetype = guide_legend(nrow = 2),
    shape = "none"
  ) +
  labs(
    title = "3. Out-of-Sample Forecast (70 pts)",
    subtitle = "Filled: train (n=30); open: holdout (98.6% PI cov)",
    x = "Day",
    y = "Infected count",
    color = NULL,
    fill = NULL,
    linetype = NULL
  ) +
  theme_blog(base_size = 9.8) +
  theme(legend.position = "bottom")

(p_sir_bg | p_sir_lev | p_sir_fc) + plot_layout(widths = c(1, 0.98, 1.15))
Figure 9: Pre-peak 5-day SIR geometry and 70-point out-of-sample forecast (sir-posterior-draws.csv and sir-forecast-ribbons.csv). Left: \((\beta, \gamma)\) posterior draws showing the \(\operatorname{Corr}(\beta, \gamma) = 0.987\) ridge along \(\beta - \gamma = 1.50\) (dotted), baseline sir.stan VI stall (x, \(\hat{k} = 5.01\)), and 0.18 s sir_pred_reparam.stan VI draws overlaying exact MCMC. Middle: initial-state lever arm between net growth \(r = \beta - \gamma\) and \(\operatorname{logit}(S_0)\). Right: 90% posterior predictive ribbons and medians trained on days 1.0–5.1 (n = 30, left of vertical dashed line) and forecast across days 5.2–15.0 (n_pred = 70).

5.3 Step 2: Editing the Stan Program (sir_reparam.stan) and Benchmark Results

sir_reparam.stan (and sir_pred_reparam.stan) applies both advisor recommendations directly. Its parameters are \((u_r, u_\gamma, z_{I,\mathrm{ref}})\): softplus coordinates for the net growth rate and the recovery rate, and the log-odds offset of the infected fraction at a reference time \(t_{\mathrm{ref}}\), the count-weighted mean observation time of the rising phase. The map \((u_r, u_\gamma, z_{I,\mathrm{ref}}) \mapsto (\beta, \gamma, S_0)\) carries exact Jacobians. The softplus link on \(r\) restricts the model to \(\beta > \gamma > 0\), a growing epidemic, and across that region the two programs agree (max |lp_rep - lp_orig| = 8.9e-10).

transformed data {
  int k_peak = 1;
  for (i in 2:n_obs) {
    if (y[i] > y[k_peak]) k_peak = i;
  }
  real w_sum = 0.0;
  real wt_sum = 0.0;
  real wy_sum = 0.0;
  for (i in 1:k_peak) {
    real w = y[i] + 0.5;
    w_sum += w;
    wt_sum += w * ts[i];
    wy_sum += w * y[i];
  }
  real t_ref = wt_sum / w_sum;
  real dt_ref = t_ref - t0;
  real i_ref = fmin(0.5, fmax(1.0 / n_pop, (wy_sum / w_sum) / n_pop));
  real logit_i_ref = logit(i_ref);
}

parameters {
  real u_r;     // softplus net growth rate: r = log1p_exp(u_r) = beta - gamma > 0
  real u_gamma; // softplus recovery rate:   gamma = log1p_exp(u_gamma) > 0
  real z_I_ref; // log-odds offset of infected fraction anchored at t_ref
}

transformed parameters {
  real r     = log1p_exp(u_r);
  real gamma = log1p_exp(u_gamma);
  real beta  = gamma + r;
  array[2] real theta = {beta, gamma};

  real u_I0 = logit_i_ref + z_I_ref - r * dt_ref;
  real I0   = inv_logit(u_I0);
  real S0   = 1.0 - I0;
  // ... identical ode_rk45 call ...
}

model {
  theta ~ lognormal(0, 1);
  target += log_inv_logit(u_r) + log_inv_logit(u_gamma);
  target += beta_lpdf(S0 | 1, 1) + log_inv_logit(u_I0) + log1m_inv_logit(u_I0);
  y ~ poisson(lambda);
}

The target += lines are the Jacobian of the change of variables: log_inv_logit(u_r) and log_inv_logit(u_gamma) are the log derivatives of the two softplus links, and log_inv_logit(u_I0) + log1m_inv_logit(u_I0) is the log absolute derivative of \(S_0 = 1 - \operatorname{logit}^{-1}(u_{I_0})\) with respect to \(z_{I,\mathrm{ref}}\). The map from \((r, \gamma)\) to \((\beta, \gamma)\) is unit triangular and contributes nothing.

Re-running fit_vi reports Nonlinear Link & Boundary Couplings: none detected on both datasets.

  • On the 15-day outbreak, PSIS k_hat drops from 0.706 (18.1% ESS) to -0.102 (85.8% ESS) in 0.27 s. Cold-start weftmc.sample from \([-2, 2]^3\) passes the Stage-1 PSIS gate (gate_k = 0.304) and runs variational_mtm directly.
  • On the 5-day pre-peak split, PSIS k_hat drops from 5.009 (0.1% ESS) to 0.579 (58.7% ESS) in 0.18 s, and every block drops into mild_nongaussian (Score res = 0.10–0.28):
PosteriorInsights (d=3, rank=3, transport=low_rank, PSIS k_hat=0.579, ESS=58.7%)

Parameter Blocks:
  Block                 Size   Max rho   Med rho  Score res Shape           
  u_r                      1      1.57      1.57     0.1043 mild_nongaussian
  u_gamma                  1      2.13      2.13     0.2827 mild_nongaussian
  z_I_ref                  1      1.99      1.99     0.1840 mild_nongaussian

Nonlinear Link & Boundary Couplings: none detected.
Code
sb <- read.csv("sir-benchmark.csv", stringsAsFactors = FALSE, na.strings = "NA")
disp_sb <- data.frame(
  Regime = sb$regime,
  Method = sb$method,
  Model = ifelse(grepl("^Baseline", sb$variant), "Baseline", "Reparam"),
  `Wall (s)` = sprintf("%.2f", sb$wall_s),
  `Kernel / PSIS` = sb$kernel_info,
  `Max R-hat` = ifelse(is.na(sb$max_rhat), "—", sprintf("%.4f", sb$max_rhat)),
  `ESS/s` = ifelse(is.na(sb$ess_per_s), "—", sprintf("%.1f", sb$ess_per_s)),
  `beta (SD)` = sb$beta_est,
  `gamma (SD)` = sb$gamma_est,
  `Holdout RMSE (Cov)` = ifelse(is.na(sb$holdout_rmse_cov), "—", sb$holdout_rmse_cov),
  check.names = FALSE
)

kable(disp_sb, row.names = FALSE, align = c("l", "l", "l", "r", "l", "r", "r", "r", "r", "r"))
Table 5: Baseline vs advisor-reparameterized SIR benchmarks (sir-benchmark.csv; 4 chains/threads, 500 + 500 MCMC draws or 2,000 VI/Pathfinder draws; simulated truth \(\beta = 2.00\), \(\gamma = 0.50\), \(R_0 = 4.00\)). Holdout Forecast reports median RMSE and 90% predictive coverage on the 70 post-training counts.
Regime Method Model Wall (s) Kernel / PSIS Max R-hat ESS/s beta (SD) gamma (SD) Holdout RMSE (Cov)
Full 15d (n=100) WeftMC VI (fit_vi) Baseline 0.23 k_hat = 0.71 (18% ESS) — — 1.993 (0.024) 0.494 (0.005) —
Full 15d (n=100) WeftMC VI (fit_vi) Reparam 0.27 k_hat = -0.10 (86% ESS) — — 1.996 (0.024) 0.494 (0.004) —
Full 15d (n=100) CmdStan Pathfinder (4p) Baseline 55.93 L-BFGS + PSIS — — 2.000 (0.024) 0.494 (0.004) —
Full 15d (n=100) CmdStan Pathfinder (4p) Reparam 0.54 L-BFGS + PSIS — — 2.000 (0.024) 0.494 (0.004) —
Full 15d (n=100) CmdStan NUTS (0.80) Baseline 4.82 NUTS (0 div) 1.0036 117.0 1.997 (0.024) 0.494 (0.004) —
Full 15d (n=100) CmdStan NUTS (0.80) Reparam 2.54 NUTS (0 div) 1.0014 395.2 1.996 (0.023) 0.494 (0.004) —
Full 15d (n=100) WeftMC sample (cold) Baseline 9.10 pnuts 1.0043 144.8 1.996 (0.024) 0.494 (0.004) —
Full 15d (n=100) WeftMC sample (VI-warm) Baseline 2.05 variational_mtm (k=0.38) 1.0007 824.2 1.996 (0.023) 0.494 (0.004) —
Full 15d (n=100) WeftMC sample (cold) Reparam 2.14 variational_mtm (k=0.30) 1.0004 845.8 1.997 (0.024) 0.494 (0.004) —
Pre-Peak 5d (n=30) WeftMC VI (fit_vi) Baseline 0.05 k_hat = 5.01 (0.1% ESS) — — 0.850 (0.009) 0.032 (0.002) 474.05 (5.7%)
Pre-Peak 5d (n=30) WeftMC VI (fit_vi) Reparam 0.18 k_hat = 0.58 (59% ESS) — — 2.005 (0.221) 0.515 (0.159) 14.63 (98.6%)
Pre-Peak 5d (n=30) CmdStan Pathfinder (4p) Baseline 21.38 L-BFGS + PSIS — — 2.020 (0.202) 0.522 (0.143) —
Pre-Peak 5d (n=30) CmdStan Pathfinder (4p) Reparam 0.33 L-BFGS + PSIS — — 1.990 (0.238) 0.502 (0.170) —
Pre-Peak 5d (n=30) CmdStan NUTS (0.80) Baseline 10.81 NUTS (Rhat > 1.01) 1.0190 23.4 1.985 (0.239) 0.497 (0.172) 14.20 (98.6%)
Pre-Peak 5d (n=30) CmdStan NUTS (0.98) Baseline 12.29 NUTS (Novik 0.98) 1.0050 20.1 1.990 (0.242) 0.502 (0.173) 14.11 (98.6%)
Pre-Peak 5d (n=30) CmdStan NUTS (0.80) Reparam 0.90 NUTS (0 div) 1.0021 450.2 1.985 (0.239) 0.499 (0.172) 14.01 (98.6%)
Pre-Peak 5d (n=30) WeftMC sample (cold) Baseline 27.86 pnuts (k=1.07) 1.0395 3.6 2.021 (0.215) 0.526 (0.152) 15.44 (98.6%)
Pre-Peak 5d (n=30) WeftMC sample (VI-warm) Baseline 17.86 pnuts (k=0.99) 1.0217 13.1 1.993 (0.205) 0.504 (0.146) 14.04 (98.6%)
Pre-Peak 5d (n=30) WeftMC sample (cold) Reparam 3.28 pnuts (k=0.93) 1.0011 355.3 1.989 (0.231) 0.500 (0.167) 14.40 (98.6%)

Reparameterizing from the 52 ms advisor report improves every engine in Table 5.

Standalone VI (weftvi and Pathfinder). On the 5-day pre-peak data, reparameterized weftvi recovers \(\beta = 2.005 \pm 0.221\) and \(\gamma = 0.515 \pm 0.159\) in 0.18 s, 67x faster than baseline CmdStan NUTS at adapt_delta = 0.98. Its forecast over the 70 held-out points has RMSE = 14.63, and its 90% predictive intervals cover 98.6% of them. Multi-path CmdStan Pathfinder drops from 55.93 s and 21.38 s, where L-BFGS line searches from \([-2, 2]^3\) repeatedly hit stiff ode_rk45 trials, to 0.54 s and 0.33 s (104x and 66x faster).

MCMC (weftmc.sample and CmdStan NUTS). On the 15-day outbreak, cold-start weftmc.sample drops from 9.10 s (144.8 ESS/s) to 2.14 s (845.8 ESS/s), and CmdStan NUTS rises from 117.0 to 395.2 ESS/s. On the 5-day pre-peak split, cold-start weftmc.sample jumps from 3.6 ESS/s (\(\widehat{R} = 1.04\)) to 355.3 ESS/s (\(\widehat{R} = 1.001\)), a 99x throughput gain. CmdStan NUTS no longer requires adapt_delta = 0.98: it converges at the default 0.80 in 0.90 s (450.2 ESS/s), a 22.4x gain in ESS/s (13.6x faster wall time) over Novik’s 12.29 s baseline.

6. When to Use What

Posteriors with \(\hat{k} < 0.5\) (\(d \lesssim 100\)). weftmc.sample switches to density-only variational_mtm while keeping chains independent. On the holdout suite that gives 0.92x–115.8x the ESS/s of CmdStan dense_e, ahead on 11 of 12 runs, with exact MCMC stationarity.

Small-\(J\) funnels and translation ridges. WeftMC avoids both the small-\(J\) funnel divergences (0 vs 2,667 across the CmdStan runs on rbest_dmap_j2 through rbest_dmap_j4) and the frozen dense-metric stalls (pupil_fit4, pupil_fit5, pm25_cluster_log_region).

Pre-flight diagnostics for hierarchical, ctsem, and nonlinear ODE models. weftmc.diagnose() flags s2z ridges, covariate-centering couplings, centering weights \(\lambda_g\), and nonlinear rate and boundary lever arms in milliseconds to seconds, before any expensive MCMC is launched. On \(N = 40{,}000\) mini-batches and 2,000-subject ctsem models (\(d = 580\)–\(2{,}162\)), Panel WAIVES and SVRG-Stein fit \(O(d \cdot r)\) approximations in about a minute or less, without forming a \(d \times d\) Hessian.

Where CmdStan diag_e or rewriting the Stan model wins. When \(\hat{k} \ge 0.5\) forces diagonal trajectory sampling on high-dimensional models (phylo_cov, park_rule) or on hard unconstrained NaN walls (loss_nl_uncorr), single-binary CmdStan diag_e avoids BridgeStan call overhead and is 1.06x–3.75x faster. On severe multi-block funnels (phylo_mv), no black-box sampler substitutes for sum_to_zero_constrain() and partial centering in the Stan program itself (Post 13).

Note

The sampler architecture in WeftMC, geometric ideas, and benchmark design are mine. Part of the C++17/Python code, benchmark framework, and this post was developed with assistance from Antigravity.

References

Beskos, Alexandros, Frank J. Pinski, Jesús María Sanz-Serna, and Andrew M. Stuart. 2011. “Hybrid Monte Carlo on Hilbert Spaces.” Stochastic Processes and Their Applications 121 (10): 2201–30. https://doi.org/10.1016/j.spa.2011.06.003.
Bou-Rabee, Nawaf, Bob Carpenter, Tore Selland Kleppe, and Sifan Liu. 2025. The Within-Orbit Adaptive Leapfrog No-U-Turn Sampler. https://arxiv.org/abs/2506.18746.
Bou-Rabee, Nawaf, Bob Carpenter, and Milo Marsden. 2024. GIST: Gibbs Self-Tuning for Locally Adaptive Hamiltonian Monte Carlo. https://arxiv.org/abs/2404.15253.
Bürkner, Paul-Christian. 2017. “brms: An R Package for Bayesian Multilevel Models Using Stan.” Journal of Statistical Software 80 (1): 1–28. https://doi.org/10.18637/jss.v080.i01.
Cai, Diana, Chirag Modi, Loucas Pillaud-Vivien, et al. 2024. “Batch and Match: Black-Box Variational Inference with a Score-Based Divergence.” Proceedings of the 41st International Conference on Machine Learning, Proceedings of machine learning research, vol. 235.
Chatzilena, Anastasia, Edwin van Leeuwen, Oliver Ratmann, Marc Baguelin, and Nikolaos Demiris. 2019. “Contemporary Statistical Inference for Infectious Disease Models Using Stan.” Epidemics 29: 100367. https://doi.org/10.1016/j.epidem.2019.100367.
Cragg, John G., and Stephen G. Donald. 1993. “Testing Identifiability and Specification in Instrumental Variable Models.” Econometric Theory 9 (2): 222–40. https://doi.org/10.1017/S0266466600007519.
Driver, Charles C. 2026. ctsem Gradient Timings: rstan, stanli, and ctsem’s Julia Engine. GitHub Gist and Stan Discourse Topic 41545. https://gist.github.com/cdriveraus/8a337860e2d3a0504bfbc282747135eb.
Driver, Charles C., Johan H. L. Oud, and Manuel C. Voelkle. 2017. “Continuous Time Structural Equation Modeling with R Package ctsem.” Journal of Statistical Software 77 (5): 1–35. https://doi.org/10.18637/jss.v077.i05.
Hoffman, Matthew D., Pavel Sountsov, Joshua V. Dillon, Ian Langmore, Dustin Tran, and Srinivas Vasudevan. 2019. NeuTra-Lizing Bad Geometry in Hamiltonian Monte Carlo Using Neural Transport. https://arxiv.org/abs/1903.03704.
Johnson, Rie, and Tong Zhang. 2013. “Accelerating Stochastic Gradient Descent Using Predictive Variance Reduction.” Advances in Neural Information Processing Systems 26: 315–23.
Kucukelbir, Alp, Dustin Tran, Rajesh Ranganath, Andrew Gelman, and David M. Blei. 2017. “Automatic Differentiation Variational Inference.” Journal of Machine Learning Research 18 (14): 1–45.
Liu, Jun S., Faming Liang, and Wing Hung Wong. 2000. “The Multiple-Try Method and Local Optimization in Metropolis Sampling.” Journal of the American Statistical Association 95 (449): 121–34. https://doi.org/10.1080/01621459.2000.10473908.
Löwner, Karl. 1934. “Über Monotone Matrixfunktionen.” Mathematische Zeitschrift 38 (1): 177–216. https://doi.org/10.1007/BF01170633.
Mandt, Stephan, Matthew D. Hoffman, and David M. Blei. 2017. “Stochastic Gradient Descent as Approximate Bayesian Inference.” Journal of Machine Learning Research 18 (134): 1–35.
Messenger, Daniel A., and David M. Bortz. 2021. “Weak SINDy for Partial Differential Equations.” Journal of Computational Physics 443: 110525. https://doi.org/10.1016/j.jcp.2021.110525.
Modi, Chirag, Charles C. Margossian, Yuling Yao, Robert M. Gower, David M. Blei, and Lawrence K. Saul. 2023. “Variational Inference with Gaussian Score Matching.” Advances in Neural Information Processing Systems 36.
Neal, Radford M. 2003. “Slice Sampling.” The Annals of Statistics 31 (3): 705–67. https://doi.org/10.1214/aos/1056562461.
Novik, Eric. 2022. Fitting a Basic SIR Model in Stan. Generable Blog. https://www.generable.com/post/fitting-a-basic-sir-model-in-stan.
Opper, Manfred, and Cédric Archambeau. 2009. “The Variational Gaussian Approximation Revisited.” Neural Computation 21 (3): 786–92. https://doi.org/10.1162/neco.2008.08-07-592.
Papaspiliopoulos, Omiros, Gareth O. Roberts, and Martin Sköld. 2007. “A General Framework for the Parametrization of Hierarchical Models.” Statistical Science 22 (1): 59–73. https://doi.org/10.1214/088342307000000014.
Parno, Matthew D., and Youssef M. Marzouk. 2018. “Transport Map Accelerated Markov Chain Monte Carlo.” SIAM/ASA Journal on Uncertainty Quantification 6 (2): 645–82. https://doi.org/10.1137/17M1134640.
Pinkney, Sean. 2024. Hierarchical Modeling in Stan: StanCon 2024 Tutorial. https://github.com/spinkney/hierarchical_model_tutorial.
Roualdes, Edward A., Brian Ward, Bob Carpenter, Adrian Seyboldt, and Seth D. Axen. 2023. “BridgeStan: Efficient in-Memory Access to the Methods of a Stan Model.” Journal of Open Source Software 8 (87): 5236. https://doi.org/10.21105/joss.05236.
Ruzayqat, Hamza, David M. Bortz, and Vanja Dukić. 2026. WAIVES: Weak-Form Asymptotically-Unbiased Instrumental-Variable Estimation for SDEs. https://arxiv.org/abs/2611.23951.
Seyboldt, Adrian, Eliot L. Carlson, and Bob Carpenter. 2026. Preconditioning Hamiltonian Monte Carlo by Minimizing Fisher Divergence. https://arxiv.org/abs/2603.18845.
Shahbaba, Babak, Shiwei Lan, Wesley O. Johnson, and Radford M. Neal. 2014. “Split Hamiltonian Monte Carlo.” Statistics and Computing 24 (3): 339–49. https://doi.org/10.1007/s11222-013-9373-1.
Shamir, Ohad, Nati Srebro, and Tong Zhang. 2014. “Communication-Efficient Distributed Optimization Using an Approximate Newton-Type Method.” Proceedings of the 31st International Conference on Machine Learning, Proceedings of machine learning research, vol. 32: 1000–1008.
Staiger, Douglas, and James H. Stock. 1997. “Instrumental Variables Regression with Weak Instruments.” Econometrica 65 (3): 557–86. https://doi.org/10.2307/2171753.
Stein, Charles M. 1981. “Estimation of the Mean of a Multivariate Normal Distribution.” The Annals of Statistics 9 (6): 1135–51. https://doi.org/10.1214/aos/1176345632.
Vehtari, Aki, Andrew Gelman, Daniel Simpson, Bob Carpenter, and Paul-Christian Bürkner. 2021. “Rank-Normalization, Folding, and Localization: An Improved \(\widehat{R}\) for Assessing Convergence of MCMC.” Bayesian Analysis 16 (2): 667–718. https://doi.org/10.1214/20-BA1221.
Vehtari, Aki, Daniel Simpson, Andrew Gelman, Yuling Yao, and Jonah Gabry. 2024. “Pareto Smoothed Importance Sampling.” Journal of Machine Learning Research 25 (72): 1–58.
Woodbury, Max A. 1950. Inverting Modified Matrices. Memorandum Report 42. Statistical Research Group, Princeton University.
Wortsman, Mitchell, Tim Dettmers, Luke Zettlemoyer, Ari Morcos, Ali Farhadi, and Ludwig Schmidt. 2023. “Stable and Low-Precision Training for Large-Scale Vision-Language Models.” Advances in Neural Information Processing Systems 36. https://arxiv.org/abs/2304.13013.
Yao, Yuling, Aki Vehtari, Daniel Simpson, and Andrew Gelman. 2018. “Yes, but Did It Work?: Evaluating Variational Inference.” Proceedings of the 35th International Conference on Machine Learning, Proceedings of machine learning research, vol. 80: 5581–90.
Zhang, Jin, and Michael A. Stephens. 2009. “A New and Efficient Estimation Method for the Generalized Pareto Distribution.” Technometrics 51 (3): 316–25. https://doi.org/10.1198/tech.2009.08017.
Zhang, Lu, Bob Carpenter, Andrew Gelman, and Aki Vehtari. 2022. “Pathfinder: Parallel Quasi-Newton Variational Inference.” Journal of Machine Learning Research 23 (306): 1–49.