Skip to main content

Inside WeftMC’s Variational Engine, Structural Diagnostics, and Automatic Stan Reparameterizer

How WeftMC’s low-rank Stein-IV operator, mini-batch WAIVES and SVRG-Stein estimators, and PSIS-gated C++17 NUTS refinement work, how weftmc.diagnose extracts collinearity ridges and centering weights from score geometry, and how weftmc.reparameterize_stan rewrites Stan 2.36+ programs with exact Jacobians.
stan
variational-inference
parameterizations
hierarchical-models
Author

Sean Pinkney

Published

December 5, 2026

1. Introduction: What Comes from the Literature and What Is Specific to WeftMC

Post 13 derived the Fisher-information geometry of sum-to-zero constraints and partial centering in hierarchical models, and Post 14 benchmarked WeftMC against CmdStan across Markov chain Monte Carlo (weftmc.sample), standalone variational inference (weftmc.fit_vi), and model reparameterization case studies. Readers looking at the C++17 and Python internals asked two concrete questions: how much of WeftMC’s variational inference comes from existing Stein or score-matching algorithms, and how do weftmc.diagnose and weftmc.reparameterize_stan detect posterior pathologies and rewrite a Stan program without breaking its target density?

First, a terminology clarification: despite the module names stein_vi.hpp and SVRG-Stein, WeftMC has no connection to Stein Variational Gradient Descent (SVGD) (Liu and Wang 2016). SVGD evolves a particle ensemble through a reproducing-kernel Hilbert space using pairwise radial-basis kernel evaluations and repulsive kernel gradients. WeftMC uses no kernel matrix and no interacting particle cloud. The name refers directly to Charles Stein’s Gaussian integration-by-parts identity (Stein 1981): for \(x \sim \mathcal{N}(m, \Sigma)\) and a differentiable log density \(\log \pi(x)\) whose boundary terms vanish at infinity,

\[ \mathbb{E}_{x \sim \mathcal{N}(m, \Sigma)}\!\left[(x - m)\,\nabla_x \log \pi(x)^\top\right] = -I_d, \qquad \mathbb{E}_{x \sim \mathcal{N}(m, \Sigma)}\!\left[-\nabla_x^2 \log \pi(x)\right] = \Sigma^{-1}. \]

Fitting a Gaussian variational approximation through this identity dates to Opper and Archambeau (Opper and Archambeau 2009). Recent score-based Gaussian variational methods include Gaussian Score Matching VI (GSM-VI) (Modi et al. 2023), Batch and Match (BaM) (Cai et al. 2024), and Fisher-divergence preconditioning for Hamiltonian Monte Carlo (Seyboldt et al. 2026). Three other ingredients also come directly from prior work: quasi-Newton variational initialization and importance resampling follow Pathfinder (Zhang et al. 2022), Pareto-smoothed importance sampling (PSIS) tail diagnostics \(\hat{k}\) follow Yao et al. (2018) and Vehtari et al. (2024), and weak-form bump test functions as instrumental variables for noisy dynamical equations come from Weak SINDy (Messenger and Bortz 2021) and WAIVES (Ruzayqat et al. 2026).

What WeftMC builds on top of those foundations comes down to four mechanisms in the variational and diagnostic core, followed by an automatic Stan source rewriter:

  1. Split-probe instrumental-variable (Stein-IV) low-rank + diagonal factorization (stein_vi.hpp). Plain Gaussian score matching sets \(z = u \sim \mathcal{N}(0, I_d)\). When \(d\) is large and \(K \ll d\) antithetic probe pairs are used both to select a rank-\(r\) subspace \(Q_k\) from the largest sample score residuals \(Y - \Lambda U\) and to estimate the residual diagonal precision \(\Lambda\) on the orthogonal complement \(\Pi_\perp = I_K - Q_k Q_k^\top\), the projection \(\Pi_\perp\) depends on \(U\) and biases the residual diagonal precision downward on the selected coordinates. WeftMC splits each probe as \(u_k = \alpha z_k + \sqrt{1 - \alpha^2}\,\varepsilon_k\) (\(\alpha = 0.8\)) and instruments \((U, Y)\) with \(Z\) via \((z_j^\top \Pi_\perp y_j)/(z_j^\top \Pi_\perp u_j)\), followed by a second \(r\)-dimensional subspace IV solve and held-out ELBO step damping.
  2. 48-gradient odd log-curvature funnel detection and \(O(d \cdot r)\) triangular transport (transport.hpp, stein_vi.hpp). Whereas GSM-VI, BaM, and Pathfinder fit symmetric Gaussians, WeftMC evaluates 24 antithetic pairs (48 gradients) and uses smoothed odd log-curvature differences \(\tfrac{1}{2}\bigl[\log\sqrt{(z_j g_j^+)^2 + 0.05^2} - \log\sqrt{((-z_j) g_j^-)^2 + 0.05^2}\bigr]\) to identify hierarchical scale parents and modulated child fibers at arbitrary dimension \(d\), fitting a triangular HierarchicalTransport (or a nonlinear subspace LowRankTransport along residual score directions) on top of \(B_0\) only when held-out reverse KL improves over the affine Gaussian.
  3. Panel WAIVES and cross-fitted SVRG-Stein for mini-batches (minibatch_vi.py). Ruzayqat, Bortz, and Dukić (Ruzayqat et al. 2026) formulated WAIVES for a single long SDE trajectory; WeftMC adapts it into a short-horizon, multi-chain panel IV across \(C \in \{8, 16\}\) dispersed chains around the mode so stochastic drift estimates \(-P_w\) without the Mandt–Hoffman–Blei gradient-noise bias (\(\Sigma_{\mathrm{SG}} \ne P_w\)) (Mandt et al. 2017). On replayable mini-batches, SVRG-Stein evaluates antithetic pairs on shared batches—canceling both the full-data SVRG anchor and zero-order mini-batch noise—and splits probes into two folds (subspace discovery vs. out-of-sample precision) to prevent subspace overfitting.
  4. PSIS-gated C++17 Stein-chart trajectory refinement and \(O(d \cdot r)\) structural diagnostics (weft_kernel.cpp, insights.py). Pathfinder and ADVI stop at static importance resampling even when \(\hat{k} \ge 0.5\) (\(\mathbb{E}[w^2] = \infty\)). WeftMC reuses the Stein-IV operator \(B_0\) both to extract closed-form \(O(d \cdot r)\) variance-inflation ridge ratios \(\rho_j = \sigma_{\mathrm{marg}, j}/\sigma_{\mathrm{cond}, j}\) and partial-centering weights \(\hat{\lambda}_g\) (weftmc.diagnose), and—whenever \(\hat{k} > 0.5\)—to precondition four short parallel C++17 NUTS chains (weft_refine_vi_stan, weft_refine_vi_callback) so skewed or boundary-coupled posteriors recover calibrated standard errors.

Pairing diagnose with weftmc.reparameterize_stan (reparam.py) closes the loop on Stan 2.36+ models: without touching the model block, it rewrites declarations in parameters, reconstructs the original variable names in dependency order inside transformed parameters, and accumulates exact log-determinants via jacobian +=. Sections 2, 3, and 4 examine fit_vi, diagnose, and reparameterize_stan in detail.


2. Inside weftmc.fit_vi: Stein-IV Precision, Funnel Transports, Mini-Batch IV, and PSIS-Gated Refinement

2.1 Two-Stage \(O(d \cdot r)\) Low-Rank + Diagonal Stein-IV (stein_vi.hpp)

Forming or inverting a dense \(d \times d\) covariance matrix costs \(O(d^2)\) memory and \(O(d^3)\) arithmetic, which rules out dense score matching once \(d\) reaches a few hundred parameters. Diagonal ADVI (Kucukelbir et al. 2017) scales in \(O(d)\) while missing posterior correlations, and L-BFGS inverse-Hessian histories in Pathfinder (Zhang et al. 2022) only span the secant directions visited by a single optimization trajectory.

WeftMC represents its Gaussian scale factor \(B_0 \in \mathbb{R}^{d \times d}\) (such that \(x = m + B_0 u\) for \(u \sim \mathcal{N}(0, I_d)\) has covariance \(\Sigma = B_0 B_0^\top\) and precision \(P = B_0^{-\top} B_0^{-1}\)) as a diagonal scale vector \(s \in \mathbb{R}_+^d\) times an identity-plus-low-rank orthogonal perturbation:

\[ B_0 = \operatorname{diag}(s)\Bigl(I_d + Q \operatorname{diag}(\beta - \mathbf{1}_r) Q^\top\Bigr), \qquad Q^\top Q = I_r, \quad \beta_a = \lambda_a^{-1/2} > 0. \]

Storing \((m, s, Q, \beta)\) takes \((2 + r)d + r\) floats. Applying \(B_0\), \(B_0^\top\), \(B_0^{-1}\), or \(B_0^{-\top}\) to a vector takes \(O(d \cdot r)\) operations without Woodbury matrix inversions (Woodbury 1950):

\[ \begin{aligned} B_0 u &= s \odot \Bigl(u + Q\bigl((\beta - \mathbf{1}_r) \odot (Q^\top u)\bigr)\Bigr), \\ B_0^{-1} w &= \tilde{w} + Q\Bigl(\bigl(\beta^{-1} - \mathbf{1}_r\bigr) \odot (Q^\top \tilde{w})\Bigr), \qquad \tilde{w} = w \oslash s, \\ \log|\det B_0| &= \sum_{j=1}^d \log s_j + \sum_{a=1}^r \log \beta_a. \end{aligned} \]

To fit \((m, s, Q, \beta)\) in fit_stein_vi, WeftMC first locates an interior anchor \(m \in \mathbb{R}^d\) via short damped L-BFGS initialized from multi-probe diagonal curvature scales \(s_j\). Given \((m, s)\) and target rank \(r\), it estimates \((Q, \beta)\) and refines \(s\) in two score-probing stages.

Stage 1: Split-probe subspace discovery and orthogonal-complement IV residual diagonal. Let \(H_{\mathrm{scaled}} = \operatorname{diag}(s)\bigl(-\nabla_x^2 \log\pi(m)\bigr)\operatorname{diag}(s)\) denote the true local precision in \(s\)-preconditioned coordinates. Stage 1 draws \(K_1 = \max(16, \min(64, r + 12))\) independent standard-normal instruments \(z_k \sim \mathcal{N}(0, I_d)\) and independent orthogonal noise vectors \(\varepsilon_k \sim \mathcal{N}(0, I_d)\), forming correlated split probes

\[ u_k = \alpha z_k + \sqrt{1 - \alpha^2}\,\varepsilon_k, \qquad \alpha = 0.8. \]

For step size \(h = 0.2\), each probe evaluates an antithetic score difference across \(m\):

\[ y_k = -\frac{s \odot \Bigl(\nabla_x \log\pi\bigl(m + h(s \odot u_k)\bigr) - \nabla_x \log\pi\bigl(m - h(s \odot u_k)\bigr)\Bigr)}{2h} \approx H_{\mathrm{scaled}}\, u_k, \]

where the central difference cancels even-order third-derivative skewness around \(m\). Given an initial diagonal precision estimate \(\Lambda = \operatorname{diag}(\lambda)\), WeftMC forms the diagonal-subtracted, correlation-scaled score residuals \(R_{\mathrm{sc}} = \Lambda^{-1/2}(Y - \Lambda U) \in \mathbb{R}^{d \times K_1}\), computes the eigendecomposition \((\mu_a, v_a)\) of the \(K_1 \times K_1\) Gram matrix \(G_k = R_{\mathrm{sc}}^\top R_{\mathrm{sc}}\), and retains directions that clear a median noise-floor threshold (ev_k > 1.8 * med_ev during alternating updates and 1.6 * med_ev on the final subspace extraction):

\[ Q_k = [v_1, \dots, v_{r_{\mathrm{eff}}}] \in \mathbb{R}^{K_1 \times r_{\mathrm{eff}}}. \]

Plain Stein score matching sets \(Z = U\). When \(d\) is large and \(K_1 \ll d\), estimating both \(Q_k\) (from the largest sample residuals of \(Y - \Lambda U\)) and the residual diagonal precision \(\Lambda\) on the orthogonal complement \(\Pi_\perp = I_{K_1} - Q_k Q_k^\top\) from the same probes makes \(\Pi_\perp\) a data-dependent function of \(U\): projecting out the directions with the largest sample score residuals systematically removes probe energy along the selected coordinates and biases \((u_{j, :}\,\Pi_\perp\,y_{j, :}^\top)/(u_{j, :}\,\Pi_\perp\,u_{j, :}^\top)\) downward. Splitting \(u_k = \alpha z_k + \sqrt{1 - \alpha^2}\,\varepsilon_k\) (\(\alpha = 0.8\)) and instrumenting \((U, Y)\) with \(Z\) breaks that selection coupling:

\[ \hat{\lambda}_j = \frac{z_{j, :}\,\Pi_\perp\,y_{j, :}^\top}{z_{j, :}\,\Pi_\perp\,u_{j, :}^\top}, \]

updating coordinate \(j\) whenever \(z_{j, :}\,\Pi_\perp\,u_{j, :}^\top > 0.15 h K_1\). Lifting the converged residual eigenvectors via orthonormalization of \(R_{\mathrm{sc}} Q_k\) produces the rank-\(r_{\mathrm{eff}}\) basis \(Q \in \mathbb{R}^{d \times r_{\mathrm{eff}}}\).

Stage 2: Targeted subspace IV solve, residual diagonal polish, and held-out ELBO damping. Once \(Q\) and the updated diagonal \(\Lambda\) are fixed, Stage 2 concentrates \(K_{\mathrm{sub}} = \max(24, 3 r_{\mathrm{eff}})\) fresh split probes \(a_k = h(\alpha \tilde{z}_k + \sqrt{1 - \alpha^2}\,\tilde{\varepsilon}_k) \in \mathbb{R}^{r_{\mathrm{eff}}}\) directly inside \(\operatorname{span}(Q)\) and solves the \(r_{\mathrm{eff}} \times r_{\mathrm{eff}}\) linear IV system

\[ H_{\mathrm{sub}} = \operatorname{sym}\!\Bigl(\bigl(Z_{\mathrm{sub}} A_{\mathrm{sub}}^\top\bigr)^{-1} \bigl(Z_{\mathrm{sub}} (Q^\top Y_{\mathrm{sub}})^\top\bigr)\Bigr). \]

Sixteen additional residual probes orthogonal to \(Q\) polish the diagonal precisions \(\lambda_j\), and WeftMC computes the preconditioned Stein mean shift \(\Delta m = B_{\mathrm{cand}} B_{\mathrm{cand}}^\top \bar{s}_{\mathrm{mean}}\) from the average score \(\bar{s}_{\mathrm{mean}}\) across the antithetic pairs. Evaluating Gaussian ELBO on held-out common-random-number draws selects the largest fractional step \(\gamma \in \{1.0, 0.5, 0.25, 0.1\}\) (damping both the mean shift \(\gamma \Delta m\) and log-precision updates \(\lambda_j^\gamma, \mu_a^\gamma\)) that strictly improves held-out evidence.

Code
ab <- read.csv("stein-iv-ablation.csv", stringsAsFactors = FALSE)
ab$dim_label <- factor(paste0("d = ", ab$dimension), levels = c("d = 100", "d = 250", "d = 500"))
ab$method <- factor(
  ab$method,
  levels = c(
    "Diagonal Curvature Only",
    "Stein-IV (rank = 4, under-ranked)",
    "Stein-IV (rank = 16, exact rank)",
    "Stein-IV (rank = 24, over-ranked)"
  )
)
ab$sd_plot <- pmax(ab$sd_rel_err_pct, 0.004)
ab$kl_plot <- pmax(ab$kl_to_truth, 1e-6)

method_cols <- c(
  "Diagonal Curvature Only" = blog_colors$red,
  "Stein-IV (rank = 4, under-ranked)" = blog_colors$gold,
  "Stein-IV (rank = 16, exact rank)" = blog_colors$blue,
  "Stein-IV (rank = 24, over-ranked)" = blog_colors$teal
)

p_kl <- ggplot(ab, aes(x = dim_label, y = kl_plot, color = method, shape = method, group = method)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 3.0) +
  scale_y_log10(
    limits = c(5e-7, 150),
    breaks = c(1e-6, 1e-4, 1e-2, 1, 100),
    labels = c("<=1e-6", "1e-4", "1e-2", "1", "100")
  ) +
  scale_color_manual(values = method_cols, name = NULL) +
  scale_shape_manual(values = c(16, 15, 17, 18), name = NULL) +
  guides(color = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  labs(
    title = "KL Divergence to Exact Posterior",
    subtitle = "Rank-16 + diagonal target (kappa > 1,400)",
    x = "Parameter dimension",
    y = "KL(q || target) [log10]"
  )

p_sd <- ggplot(ab, aes(x = dim_label, y = sd_plot, color = method, shape = method, group = method)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 3.0) +
  scale_y_log10(
    limits = c(0.002, 100),
    breaks = c(0.004, 0.01, 0.1, 1, 10, 100),
    labels = c("<0.005%", "0.01%", "0.1%", "1%", "10%", "100%")
  ) +
  scale_color_manual(values = method_cols, name = NULL) +
  scale_shape_manual(values = c(16, 15, 17, 18), name = NULL) +
  guides(color = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  labs(
    title = "Marginal SD Relative Error",
    subtitle = "Median |SD_vi - SD_true| / SD_true (%)",
    x = "Parameter dimension",
    y = "Median relative SD error [log10]"
  )

(p_kl + p_sd) +
  plot_layout(guides = "collect") &
  theme(
    legend.position = "bottom",
    legend.text = element_text(size = 9.5),
    plot.title = element_text(size = 13)
  )
Figure 1: Recovery of exact rank-16-plus-diagonal posteriors with condition number > 1,400 across dimensions d = 100, 250, and 500. Left: KL divergence KL(q || pi) on a log10 scale. Right: median relative error (%) in marginal posterior standard deviations. Matching or exceeding the true rank (r = 16 or r = 24) drives marginal SD error below 0.11% in 62-166 ms, while over-specifying rank (r = 24) truncates noise eigenvalues cleanly.
Code
disp_ab <- data.frame(
  `d` = ab$dimension,
  Method = as.character(ab$method),
  `Med SD Err (%)` = ifelse(ab$sd_rel_err_pct < 0.005, "< 0.005", sprintf("%.3f", ab$sd_rel_err_pct)),
  `Cov Rel Fro Err` = ifelse(ab$frob_cov_rel_err < 0.0005, "< 0.0005", sprintf("%.4f", ab$frob_cov_rel_err)),
  `KL(q || pi)` = ifelse(ab$kl_to_truth <= 1e-6, "<= 1e-6", sprintf("%.5f", ab$kl_to_truth)),
  `Grad Calls` = ab$grad_calls,
  `Wall (ms)` = ifelse(is.na(ab$wall_ms), "—", sprintf("%.1f", ab$wall_ms)),
  check.names = FALSE
)

kable(disp_ab, row.names = FALSE, align = c("r", "l", "r", "r", "r", "r", "r"))
Table 1: Low-rank + diagonal Stein-IV recovery on conditioned rank-16-plus-diagonal posteriors across d = 100, 250, and 500.
d Method Med SD Err (%) Cov Rel Fro Err KL(q || pi) Grad Calls Wall (ms)
100 Diagonal Curvature Only 56.112 0.9660 41.43820 200 —
100 Stein-IV (rank = 4, under-ranked) 28.688 0.7464 38.93157 2204 60.3
100 Stein-IV (rank = 16, exact rank) 0.107 0.0095 0.01007 2012 67.5
100 Stein-IV (rank = 24, over-ranked) 0.018 0.0018 0.00095 2412 138.9
250 Diagonal Curvature Only 34.018 0.9245 52.45550 500 —
250 Stein-IV (rank = 4, under-ranked) 9.798 1.6711 39.49893 1918 78.6
250 Stein-IV (rank = 16, exact rank) 0.011 0.0016 0.00017 2030 100.0
250 Stein-IV (rank = 24, over-ranked) 0.014 0.0018 0.00026 2286 166.5
500 Diagonal Curvature Only 20.219 0.8793 58.71420 1000 —
500 Stein-IV (rank = 4, under-ranked) 10.587 0.8631 23.96408 1735 94.7
500 Stein-IV (rank = 16, exact rank) 0.011 0.0026 0.00153 2167 133.9
500 Stein-IV (rank = 24, over-ranked) < 0.005 < 0.0005 <= 1e-6 967 62.2

Figure 1 and Table 1 show why matching the low-rank subspace matters. On a synthetic Gaussian with 16 correlated spikes and condition number above \(1{,}400\), diagonal curvature misses marginal standard deviations by \(20.2\%\)–\(56.1\%\) (KL \(= 41.4\)–\(58.7\)), and truncating at \(r = 4\) leaves KL \(= 24.0\)–\(39.5\). At \(r = 16\), C++17 fit_stein_vi recovers marginal standard deviations to \(0.011\%\)–\(0.107\%\) in \(67.5\)–\(133.9\text{ ms}\). Over-specifying \(r = 24\) does not overfit noise directions because the \(1.6\,\operatorname{med}(\mu)\) filter discards flat eigenvalues; at \(d = 500\), \(r = 24\) converges in 967 gradient evaluations (fewer than \(2d = 1{,}000\)) and \(62.2\text{ ms}\).

2.2 Antithetic Odd Log-Curvature and Hierarchical Funnel Transports (transport.hpp)

GSM-VI (Modi et al. 2023), BaM (Cai et al. 2024), and Pathfinder (Zhang et al. 2022) fit symmetric Gaussian approximations, which cannot represent Neal’s funnel (Neal 2003; Betancourt and Girolami 2015) where a log-scale parent \(\ell = \log\tau\) rescales the conditional variance of child fibers \(x_{\mathrm{child}} \mid \ell \sim \mathcal{N}(0, e^{2\ell} I)\) across orders of magnitude. Evaluating whether coordinate \(a\) acts as a scale parent for coordinate \(j\) via third-derivative tensors would cost \(O(d^2)\) Hessian-vector products.

WeftMC detects both funnel parent-fiber pairs and residual nonlinear score directions in 48 gradient evaluations (\(P = 24\) antithetic standard-normal draws \(z_p \sim \mathcal{N}(0, I_d)\)) inside analyze_residuals_parallel (stein_vi.hpp). At each pair \(x_p^\pm = m \pm B_0 z_p\), it pulls the target gradient back to whitened coordinates, \(g_{z, p}^\pm = B_0^\top \nabla_x \log\pi(x_p^\pm)\), records the Gaussian score residuals \(g_{z, p}^\pm \mp z_p\), and computes a smoothed odd directional log-curvature contrast on every coordinate \(j\):

\[ d_{p, j} = \frac{1}{2}\left[\log\sqrt{\bigl(z_{p, j}\,g_{z, p, j}^+\bigr)^2 + \epsilon^2} - \log\sqrt{\bigl((-z_{p, j})\,g_{z, p, j}^-\bigr)^2 + \epsilon^2}\right], \qquad \epsilon = 0.05. \]

For any symmetric density in whitened space—whether Gaussian, Student-\(t\), or symmetric logistic—the directional virial terms at \(+z_p\) and \(-z_p\) are equal in distribution, so \(d_{p, j}\) has mean zero. Under a hierarchical funnel \(\tilde{z}_j = e^{\frac{1}{2} c_{j a} z_a} z_j\), flipping \(z_p \mapsto -z_p\) flips the sign of the parent \(z_{p, a}\), multiplying the conditional precision along fiber \(j\) at \(+z_p\) and dividing it at \(-z_p\). Greedy orthogonalized regression of active high-curvature fibers \(d_{:, j}\) on candidate coordinates \(z_{:, a}\) identifies up to \(\min(\max(r, 4), 8)\) scale parents \(S_{\mathrm{parents}}\) and their modulated fiber set \(S_{\mathrm{fibers}}\) at arbitrary dimension \(d\) without increasing the 48-gradient budget.

Depending on what analyze_residuals_parallel finds, WeftMC fits one of two \(O(d \cdot r)\) nonlinear transports on top of \(B_0\) via proximal L-BFGS (transport.hpp):

  • Triangular HierarchicalTransport (when scale parents and modulated fibers are detected). WeftMC decouples the parent columns in \(B_0\) (decouple_parent_basis) so parents precede fibers cleanly, then fits per-parent shift/skewness and a parent-to-fiber scale matrix \(C \in \mathbb{R}^{|S_{\mathrm{fibers}}| \times |S_{\mathrm{parents}}|}\) mapping \(\tilde{z}_j = \exp\bigl(\tfrac{1}{2}\operatorname{clip}(c_j^\top z_{\mathrm{parents}}, -3, 3)\bigr) z_j\) and \(x = m + B_{\mathrm{hier}} \tilde{z}\), with exact \(O(d \cdot r)\) triangular log-Jacobian.
  • Nonlinear subspace LowRankTransport (when no scale parents exist, yet non-Gaussian score-residual directions remain). Along the top singular vectors of the whitened score residuals \(g_{z, p}^\pm \mp z_p\), WeftMC fits a coupled nonlinear subspace warp on top of \(B_0\) (skipping shared coupling at \(d \ge 64\) when baseline log-ratio dispersion exceeds \(1.85\)).

In either branch, WeftMC accepts the nonlinear map over the affine Gaussian (m, B_0) only when reverse KL improves on independent held-out Gaussian draws; if importance weights still degenerate (\(\widehat{\mathrm{ESS}}_{\mathrm{PSIS}}/M < 0.02\)), fit_vi falls back to a safe diagonal Gaussian around the anchor (diagonal_fallback).

2.3 Mini-Batch Score Matching: Panel WAIVES and Cross-Fitted SVRG-Stein (minibatch_vi.py)

When \(N\) is large enough that each full likelihood evaluation is expensive, replacing \(\nabla_x \log\pi(x)\) with a stochastic mini-batch score \(\hat{g}_{\mathcal{B}}(x) = \nabla_x \log p(x) + \frac{N}{|\mathcal{B}|}\sum_{i \in \mathcal{B}} \nabla_x \log p(y_i \mid x)\) breaks naive score matching in two ways:

  1. SGD stationary covariance mismatch. Treating constant-step SGD iterates as approximate posterior draws (Mandt et al. 2017) produces stationary covariance satisfying \(P \Sigma_{\mathrm{SGD}} + \Sigma_{\mathrm{SGD}} P \propto \Sigma_{\mathrm{SG}}\), which recovers \(\Sigma = P^{-1}\) only under Fisher-efficiency alignment \(\Sigma_{\mathrm{SG}} \propto P\). Under misspecification, heteroskedasticity, or hierarchical priors where prior curvature dominates likelihood noise on latent blocks, \(\Sigma_{\mathrm{SG}} \ne P\) inflates noisy coordinates and collapses weakly noisy hierarchical coordinates.
  2. Errors-in-variables attenuation in OLS score regression. Regressing noisy scores \(\hat{g}_t\) on noisy stochastic trajectory positions \(x_t\) biases precision estimates because trajectory positions accumulate past mini-batch gradient errors, while forming \(\hat{g}_t \hat{g}_t^\top\) adds positive-definite mini-batch variance \(\mathbb{E}[\eta_t \eta_t^\top] = \Sigma_{\mathrm{SG}}\) directly onto \(P^2\).

WeftMC provides two instrumental-variable estimators in minibatch_vi.py depending on whether occasional full-data anchor passes are affordable:

  • Panel WAIVES (pure mini-batch streaming, zero full-data sweeps). Ruzayqat, Bortz, and Dukić (Ruzayqat et al. 2026) formulated WAIVES (building on Weak SINDy (Messenger and Bortz 2021)) for a single long continuous-time SDE trajectory. WeftMC adapts it into a short-horizon, multi-chain panel IV across \(C \in \{8, 16\}\) dispersed chains around an averaged warm-up mode using constant-step per-block StableAdamW updates (Wortsman et al. 2023) with unit root-mean-square gradient clipping, so drift directly estimates \(-P_w\) without Mandt–Hoffman–Blei gradient-noise bias (\(\Sigma_{\mathrm{SG}} \ne P_w\)). Along each chain’s trajectory \((x_{c, t}, \hat{g}_{c, t})\), Panel WAIVES convolves states and scores with smooth compactly supported bump weights \(\phi(\tau) \propto \exp(-1 / (1 - \tau^2))\) on \(\tau \in (-1, 1)\) over disjoint windows of length \(L = 8\) separated by gap \(g = 2\). Past-window filtered displacements \(z_{c, w}^{\mathrm{past}}\) depend only on mini-batches up to step \(t_w - g\), whereas future-window filtered scores \(\tilde{g}_{c, w}^{\mathrm{curr}}\) use fresh mini-batches from \(t_w\) onward. Because the mini-batch sampling errors in the two windows are independent,

    \[ \mathbb{E}\!\left[Z_{\mathrm{inst}}^\top G_{\mathrm{curr}}\right] = \mathbb{E}\!\left[Z_{\mathrm{inst}}^\top \bar{G}_{\mathrm{true}}\right] \approx -\mathbb{E}\!\left[Z_{\mathrm{inst}}^\top \Delta X_{\mathrm{curr}}\right] P_w, \]

    eliminating \(\Sigma_{\mathrm{SG}}\) in expectation without any full-dataset pass. To prevent ill-conditioned instrument denominators from blowing up variance—the classical weak-instrument failure analyzed by Cragg and Donald (Cragg and Donald 1993) and Staiger and Stock (Staiger and Stock 1997)—WeftMC checks the minimum singular value of the cross-moment matrix inside the active subspace and applies Tikhonov damping only when conditioning falls below threshold. On the \(N = 40{,}000\), \(d = 60\) benchmark in Post 14, Panel WAIVES reaches \(\mathrm{KL}(q \,\|\, \pi) = 0.25\) versus \(24.78\) for Panel OLS on well-specified logistic regression (a 97x reduction) and \(0.27\) versus \(27.27\) under heteroskedastic student-\(t\) contamination (a 102x reduction).

  • SVRG-Stein (replayable mini-batches plus periodic full-data anchors). When mini-batches are replayable and two or three full-data passes are affordable, SVRG-Stein computes an exact Johnson–Zhang (Johnson and Zhang 2013) anchor gradient \(\bar{g}(m) = \nabla_x \log\pi(m)\) to locate \(m\) without bias, then evaluates antithetic probe pairs \(m \pm \delta_k\) on the same shared mini-batch \(\mathcal{B}_k\):

    \[ \Delta \hat{g}_k = \frac{\hat{g}_{\mathcal{B}_k}(m + \delta_k) - \hat{g}_{\mathcal{B}_k}(m - \delta_k)}{2}. \]

    Sharing \(\mathcal{B}_k\) across \(+ \delta_k\) and \(- \delta_k\) cancels both the full-data SVRG anchor \(\bar{g}(m)\) and the zero-order mini-batch score noise \(\hat{g}_{\mathcal{B}_k}(m) - \bar{g}(m)\) identically, leaving only \(O(\|\delta_k\|)\) curvature variance instead of \(O(1)\) gradient variance. Splitting the probe pairs into two equal folds \(A\) and \(B\)—using fold \(A\) for subspace discovery \(Q\) and fold \(B\) for out-of-sample precision eigenvalues \(\beta\)—prevents subspace overfitting on finite mini-batches.

2.4 PSIS-Gated C++17 Stein-Chart NUTS Refinement (weft_kernel.cpp)

Variational approximations that stop at a Gaussian or triangular map—including Pathfinder (Zhang et al. 2022), ADVI (Kucukelbir et al. 2017), and unrefined Stein-IV (refine=False)—share a structural failure mode when posterior tails are heavier or more skewed than the variational family. Drawing \(M\) samples \(z_m \sim g(z)\) (in WeftMC, the defensive mixture \(0.93\,\mathcal{N}(0, I_d) + 0.07\,t_6(0, 1.25^2 I_d)\)) and forming importance weights \(w_m = \pi(T(z_m))|\det J_T(z_m)| / g(z_m)\) yields finite-variance weights only when the Pareto tail shape satisfies \(\hat{k} < 0.5\) (Vehtari et al. 2024). Once \(\hat{k} \ge 0.5\), \(\mathbb{E}[w^2] = \infty\): a few extreme weights carry most of the probability mass, effective sample size collapses, and importance-resampled posterior standard deviations shrink well below the true uncertainty.

By default (refine="auto"), weftmc.fit_vi uses \(\hat{k}\) as an automatic C++17 gate:

  • \(\hat{k} \le 0.5\) (zero extra evaluations). The Stein-IV or hierarchical transport covers the posterior with finite weight variance. fit_vi returns Pareto-smoothed importance-resampled draws immediately, adding zero gradient calls.
  • \(\hat{k} > 0.5\) (4-chain C++17 Stein-chart NUTS refinement). fit_vi calls weft_refine_vi_stan (for BridgeStan models) or weft_refine_vi_callback (for custom Python targets) in weft_kernel.cpp. Four chains launch in parallel across WeftMC’s 16 MB stack-allocated POSIX WorkerPool threads, seeded independently via SplitMix64 (seed + 104729 * (chain + 1)) and initialized at top-weight PSIS draws pulled back to whitened Stein-IV coordinates \(u = B_0^{-1}(x - m)\). Because \(B_0\) has already whitened the local precision to \(B_0^\top P B_0 \approx I_d\), unit-metric NUTS with dual-averaged step size (max_treedepth = 7, default 64 warmup + 128 sampling transitions per chain, yielding 512 draws) traverses curved ridges and skewed boundaries without spending hundreds of iterations learning a mass matrix.
Code
vr <- read.csv("vi-se-recovery.csv", stringsAsFactors = FALSE)
vr <- vr[order(vr$k_hat), ]
vr$label <- sprintf("%s [k = %+.2f]", vr$model, vr$k_hat)
vr$label <- factor(vr$label, levels = vr$label)
vr$regime <- ifelse(vr$k_hat <= 0.5, "k_hat <= 0.5 (0 extra grads)", "k_hat > 0.5 (4-chain C++17 NUTS)")

vr_long_se <- rbind(
  data.frame(label = vr$label, mode = "Unrefined PSIS-SIR (refine = False)", ratio = vr$unref_se_ratio, k_hat = vr$k_hat),
  data.frame(label = vr$label, mode = "Default fit_vi (refine = \"auto\")", ratio = vr$auto_se_ratio, k_hat = vr$k_hat)
)
vr_long_se$mode <- factor(
  vr_long_se$mode,
  levels = c("Unrefined PSIS-SIR (refine = False)", "Default fit_vi (refine = \"auto\")")
)

vr_seg <- subset(vr, k_hat > 0.5)

p_se <- ggplot() +
  geom_vline(xintercept = 1.0, linetype = "dashed", color = blog_colors$text_light, linewidth = 0.5) +
  geom_hline(yintercept = 3.5, linetype = "dotted", color = blog_colors$text_light, linewidth = 0.45) +
  geom_segment(
    data = vr_seg,
    aes(x = unref_se_ratio, xend = auto_se_ratio, y = label, yend = label),
    color = blog_colors$teal,
    linewidth = 0.9,
    arrow = arrow(length = unit(0.16, "cm"), type = "closed")
  ) +
  geom_point(
    data = vr_long_se,
    aes(x = ratio, y = label, color = mode, shape = mode),
    size = 3.1
  ) +
  scale_y_discrete(limits = levels(vr$label)) +
  scale_color_manual(
    values = c(
      "Unrefined PSIS-SIR (refine = False)" = blog_colors$red,
      "Default fit_vi (refine = \"auto\")" = blog_colors$teal
    ),
    name = NULL
  ) +
  scale_shape_manual(
    values = c(
      "Unrefined PSIS-SIR (refine = False)" = 16,
      "Default fit_vi (refine = \"auto\")" = 17
    ),
    name = NULL
  ) +
  scale_x_continuous(limits = c(0.18, 1.15), breaks = c(0.25, 0.50, 0.75, 1.00)) +
  annotate("text", x = 0.20, y = 2.65, label = "k_hat <= 0.5: 0 extra grads", hjust = 0, size = 3.0, color = blog_colors$text_light) +
  annotate("text", x = 0.20, y = 5.05, label = "k_hat > 0.5: C++17 NUTS refine", hjust = 0, size = 3.0, color = blog_colors$teal, fontface = "bold") +
  labs(
    title = "Standard-Error Calibration",
    subtitle = "VI SD / Reference NUTS SD",
    x = "Estimated SD / Reference NUTS SD",
    y = NULL
  )

vr_long_wall <- rbind(
  data.frame(label = vr$label, mode = "Unrefined PSIS-SIR (refine = False)", wall = vr$unref_wall_s),
  data.frame(label = vr$label, mode = "Default fit_vi (refine = \"auto\")", wall = vr$auto_wall_s)
)
vr_long_wall$mode <- factor(
  vr_long_wall$mode,
  levels = c("Unrefined PSIS-SIR (refine = False)", "Default fit_vi (refine = \"auto\")")
)

p_wall <- ggplot() +
  geom_hline(yintercept = 3.5, linetype = "dotted", color = blog_colors$text_light, linewidth = 0.45) +
  geom_segment(
    data = vr_seg,
    aes(x = unref_wall_s, xend = auto_wall_s, y = label, yend = label),
    color = blog_colors$teal,
    linewidth = 0.85,
    arrow = arrow(length = unit(0.15, "cm"), type = "closed")
  ) +
  geom_point(
    data = vr_long_wall,
    aes(x = wall, y = label, color = mode, shape = mode),
    size = 3.1
  ) +
  scale_y_discrete(limits = levels(vr$label)) +
  scale_x_log10(
    limits = c(0.002, 5.5),
    breaks = c(0.003, 0.03, 0.3, 3),
    labels = c("3ms", "30ms", "0.3s", "3s")
  ) +
  scale_color_manual(
    values = c(
      "Unrefined PSIS-SIR (refine = False)" = blog_colors$red,
      "Default fit_vi (refine = \"auto\")" = blog_colors$teal
    ),
    name = NULL
  ) +
  scale_shape_manual(
    values = c(
      "Unrefined PSIS-SIR (refine = False)" = 16,
      "Default fit_vi (refine = \"auto\")" = 17
    ),
    name = NULL
  ) +
  labs(
    title = "Total Wall-Clock Time",
    subtitle = "Runtime in seconds (log10 scale)",
    x = "Wall-clock time [log10]",
    y = NULL
  ) +
  theme(axis.text.y = element_blank(), axis.ticks.y = element_blank())

(p_se + p_wall) +
  plot_layout(widths = c(1.22, 1.0), guides = "collect") &
  theme(
    legend.position = "bottom",
    legend.text = element_text(size = 9.5),
    plot.title = element_text(size = 13)
  )
Figure 2: Effect of PSIS-gated C++17 Stein-chart NUTS refinement (refine = ‘auto’) across seven posteriors ordered by unrefined PSIS k_hat. Left: ratio of estimated posterior standard deviation to long-run reference NUTS standard deviation (ideal = 1.0). Below k_hat = 0.5, refine = ‘auto’ performs zero extra evaluations; above k_hat = 0.5, short C++17 trajectories in the Stein-IV chart correct severe importance-sampling standard-error compression. Right: total wall-clock runtime (seconds, log10 scale).
Code
disp_vr <- data.frame(
  Model = vr$model,
  Param = vr$param,
  `PSIS k_hat` = sprintf("%+.3f", vr$k_hat),
  `Extra Grads` = format(vr$extra_grads, big.mark = ","),
  `Ref Mean (SD)` = sprintf("%.3f (%.3f)", vr$ref_mean, vr$ref_sd),
  `Unref Mean (SD)` = sprintf("%.3f (%.3f)", vr$unref_mean, vr$unref_sd),
  `Auto Mean (SD)` = sprintf("%.3f (%.3f)", vr$auto_mean, vr$auto_sd),
  `SD Ratio (Unref -> Auto)` = sprintf("%.2f -> %.2f", vr$unref_se_ratio, vr$auto_se_ratio),
  `Wall s (Unref -> Auto)` = sprintf("%.3f -> %.3f", vr$unref_wall_s, vr$auto_wall_s),
  check.names = FALSE
)

kable(disp_vr, row.names = FALSE, align = c("l", "l", "r", "r", "r", "r", "r", "r", "r"))
Table 2: PSIS-gated C++17 Stein-chart NUTS refinement across models below and above k_hat = 0.5.
Model Param PSIS k_hat Extra Grads Ref Mean (SD) Unref Mean (SD) Auto Mean (SD) SD Ratio (Unref -> Auto) Wall s (Unref -> Auto)
funnel (reparam) q -1.657 0 0.000 (3.000) 0.040 (2.957) 0.040 (2.957) 0.99 -> 0.99 0.005 -> 0.003
arK (reparam) sigma +0.192 0 0.150 (0.008) 0.150 (0.008) 0.150 (0.008) 0.98 -> 0.98 0.034 -> 0.034
arma11 (reparam) phi +0.248 0 0.957 (0.023) 0.957 (0.023) 0.957 (0.023) 1.02 -> 1.02 0.028 -> 0.028
one_comp_mm_elim_abs K_m +0.604 23,101 2.398 (4.836) 1.597 (2.478) 2.114 (3.803) 0.51 -> 0.79 0.589 -> 3.524
eight_schools (reparam) tau +0.608 35,844 3.686 (3.281) 3.361 (2.947) 3.436 (2.966) 0.90 -> 0.90 0.008 -> 0.034
banana_2d z2 +0.637 45,046 0.000 (1.629) -0.883 (0.419) -0.156 (1.228) 0.26 -> 0.75 0.003 -> 0.027
sir_pred (reparam) R_0 +0.935 21,642 4.467 (1.740) 4.340 (1.565) 4.481 (1.829) 0.90 -> 1.05 0.181 -> 0.426

Figure 2 and Table 2 show both sides of the gate. On funnel (reparam) (\(\hat{k} = -1.657\)), arK (reparam) (\(\hat{k} = +0.192\)), and arma11 (reparam) (\(\hat{k} = +0.248\)), refine="auto" executes zero extra gradients and matches reference NUTS standard deviations to within \(2\%\) in \(3\)–\(34\text{ ms}\). Above \(\hat{k} = 0.5\), static importance resampling understates uncertainty: on Rosenbrock’s banana_2d (\(\hat{k} = +0.637\)), refine=False puts \(\operatorname{SD}(z_2)\) at \(25.7\%\) of truth (\(-0.883 \pm 0.419\) vs. \(0.000 \pm 1.629\)), while refine="auto" lifts the ratio to \(75.4\%\) (\(-0.156 \pm 1.228\)) in \(27\text{ ms}\). On the stiff Michaelis–Menten ODE one_comp_mm_elim_abs (\(\hat{k} = +0.604\)), \(\operatorname{SD}(K_m)\) rises from \(51.2\%\) to \(78.6\%\) of reference NUTS in \(3.52\text{ s}\), and on sir_pred (reparam) (\(\hat{k} = +0.935\)), \(\operatorname{SD}(R_0)\) moves from \(89.9\%\) to \(105.1\%\) in \(0.43\text{ s}\).

One limitation of coordinate-space optimization is worth stating directly. On centered eight_schools (theta ~ normal(mu, tau)), the joint density in unconstrained \((\mu, \log\tau, \theta)\) diverges to \(+\infty\) along the funnel neck as \(\tau \to 0\) and \(\theta_j \to \mu\). Any mode-seeking anchor finder in centered coordinates collapses to \(\tau \approx 10^{-9}\), where local curvature is degenerate before refinement even begins. Fixing a centered funnel requires changing the parameterization itself—which is why eight_schools (reparam) in Table 2 is produced by weftmc.diagnose and weftmc.reparameterize_stan.


3. How weftmc.diagnose Diagnoses Parameterizations Without Running MCMC

weftmc.diagnose(target) runs fit_vi(..., refine=False) to obtain the Stein-IV operator \(B_0 = \operatorname{diag}(s)(I_d + Q\operatorname{diag}(\beta - \mathbf{1}_r)Q^\top)\) and combines it with structural metadata from StanTarget (insights.py, stan_io.py). Every geometric quantity below is computed in \(O(d \cdot r)\) operations without forming a dense \(d \times d\) covariance or precision matrix and without running MCMC trajectories.

3.1 BridgeStan Memory-Order Coordinate Resolution (resolve_unconstrained_names)

Associating columns of \(B_0\) with named Stan parameter blocks hits a memory-layout trap in BridgeStan (Roualdes et al. 2023). Calling param_names(include_tp=False, include_gq=False) returns constrained scalar names in column-major order—for array[K] vector[M] beta, it lists beta.1.1, beta.2.1, ..., beta.K.1, beta.1.2, ...—whereas Stan’s serializer flattens the unconstrained vector in declaration order (beta[1][1..M], then beta[2][1..M]), and constrained types like simplex[M] or sum_to_zero_vector[M] map \(M - 1\) unconstrained coordinates onto \(M\) constrained scalars.

Naive string indexing scrambles block assignments whenever arrays of vectors or constrained vectors appear. Instead, resolve_unconstrained_names in stan_io.py evaluates a base constrained state \(c^{(0)} = \operatorname{param\_constrain}(\mathbf{0})\) with include_tp=False, include_gq=False, then perturbs one unconstrained coordinate \(e_j\) at a time by \(0.37\) and checks which constrained entries move by more than \(10^{-12}\). If a perturbation moves a single scalar (alpha), coordinate \(j\) receives that exact name; if it moves multiple entries sharing a container (b.1 and b.2 in sum_to_zero_vector[2] b), coordinates assigned to that container are numbered sequentially (b[1]). Because include_tp=False and include_gq=False are set on every call, transformed parameters and generated quantities—where ODE solvers and state-space recursions live—never execute during coordinate mapping.

3.2 Variance-Inflation Ratios, s2z Translation Ridges, and Covariate Centering

Let \(e_j\) be the \(j\)-th standard basis vector. Under \(\Sigma = B_0 B_0^\top\) and \(P = B_0^{-\top} B_0^{-1}\), the marginal variance of coordinate \(j\) is \(\Sigma_{jj} = \|B_0^\top e_j\|_2^2\), and its conditional precision holding all other \(d - 1\) parameters fixed is \(P_{jj} = \|B_0^{-1} e_j\|_2^2\). WeftMC computes the exact marginal scale, conditional scale, and variance-inflation ridge ratio in \(O(d \cdot r)\) time:

\[ \sigma_{\mathrm{marg}, j} = \|B_0^\top e_j\|_2, \qquad \sigma_{\mathrm{cond}, j} = \|B_0^{-1} e_j\|_2^{-1}, \qquad \rho_j = \frac{\sigma_{\mathrm{marg}, j}}{\sigma_{\mathrm{cond}, j}} = \sqrt{\Sigma_{jj} P_{jj}} \ge 1. \]

A coordinate uncorrelated with the rest of the posterior has \(\rho_j = 1\). A parameter trapped on a linear collinearity ridge has marginal spread much wider than its conditional slice width (\(\rho_j \gg 1\)): if \(\rho_a = 15\), a Gibbs or diagonal-metric step along coordinate \(a\) is confined to \(1/15\) of its marginal standard deviation.

To identify which parameter block creates that ridge, diagnose groups unconstrained coordinates by base Stan block name and computes for each vector block \(g\) (\(|g| \ge 2\)) its whitened group-sum loading \(v_g = B_0^\top \mathbf{1}_g \in \mathbb{R}^d\), where \(\mathbf{1}_g = \sum_{i \in g} e_i\). For any scalar anchor \(a\) with \(\rho_a > 4.0\) and whitened loading \(v_a = B_0^\top e_a\), their marginal correlation with the block sum is \((v_a^\top v_g) / (\|v_a\|_2 \|v_g\|_2)\). Two filters prevent false positives:

  1. Hyperparameter partial-correlation conditioning. On hierarchical models, a log-scale parameter \(\log\tau\) can correlate marginally with both an intercept and the sum of non-centered effects through skewness. WeftMC collects all positive scale-like scalar blocks \(H\) (exp or lower_bound constraints) and projects \(v_a\) and \(v_g\) orthogonal to \(\operatorname{span}(\{B_0^\top e_h : h \in H\})\) via a small \(|H| \times |H|\) Cholesky solve, isolating pure translation ridges at fixed \((\tau, \sigma)\).

  2. Uniform-loading coherence. If a scalar correlates with only one element of a vector (such as an AR lag coefficient) rather than with the uniform sum \(\sum_{i \in g} x_i\), imposing sum_to_zero_vector across all of \(g\) is wrong. Letting \(c_i = \operatorname{Corr}(a, x_i \mid H)\) for \(i \in g\), WeftMC requires the participation coherence

    \[ \mathrm{coherence}(a, g) = \frac{\sum_{i \in g} c_i^2}{|g| \max_{i \in g} c_i^2} \ge 0.30 \]

    together with \(|\operatorname{Corr}(a, \sum_{i \in g} x_i \mid H)| \ge 0.65\) before flagging an s2z ridge.

When two blocks \(A\) and \(B\) have the same size \(K \ge 1\) and share strong component-wise correlation \(|\operatorname{Corr}(\alpha_k, \beta_k \mid H)| \ge 0.75\)—the classic signature of an uncentered covariate predictor \(\alpha_k + \beta_k x_n\)—diagnose instead emits a covariate_centering recommendation with the empirical centering shift that orthogonalizes the pair:

\[ \hat{c}_k = -\frac{\operatorname{Cov}(\alpha_k, \beta_k)}{\operatorname{Var}(\beta_k)} = -\frac{v_{\alpha_k}^\top v_{\beta_k}}{\|v_{\beta_k}\|_2^2} \approx \bar{x}_k. \]

Running weftmc.diagnose on a \(J = 10\)-group, \(N = 160\) non-centered varying-intercept model (y ~ normal(alpha + tau * z[g], sigma) with exponential(1) priors on tau and sigma) produces the following output in \(25\text{ ms}\):

PosteriorInsights (d=13, rank=13, transport=affine, PSIS k_hat=1.247, ESS=2.0%)

Parameter Blocks:
  Block                 Size   Max rho   Med rho  Score res Shape           
  alpha                    1      5.68      5.68     7.8352 skewed_or_funnel
  tau                      1      2.59      2.59     2.8551 skewed_or_funnel
  sigma                    1      1.01      1.01     0.2317 mild_nongaussian
  z                       10      2.55      2.10     0.7331 skewed_or_funnel

Sum-to-Zero (s2z) Collinearity Ridges:
  - alpha (rho=5.68) <-> z[10] (corr=-0.984, coherence=1.00, mult=14.61):
    Apply sum_to_zero_vector (s2z) constraint to z to break translation ridge with alpha (rho=5.7)

Partial-Centering Weights:
  - z[10]: lambda=0.986 -> centered_or_s2z_recommended (Use centered parameterization + sum_to_zero_vector (s2z))

Reparameterization Tricks:
  - tau (uncentered_exponential_icdf [auto]): Decouple exponential prior on tau (rate=1) via
    overflow-safe inverse-CDF z_tau ~ logistic(0, 1): tau = log1p_exp(-z_tau) / (1)
  - sigma (uncentered_exponential_icdf [auto]): Decouple exponential prior on sigma (rate=1) via
    overflow-safe inverse-CDF z_sigma ~ logistic(0, 1): sigma = log1p_exp(-z_sigma) / (1)

3.3 Why \(J = 2\) Groups Need Reference-Relative Offsets Instead of sum_to_zero_vector[2]

A subtle edge case arises when a grouping factor has only \(J = 2\) levels (for instance, treatment vs. control, or one densely observed reference clinic and one sparse satellite clinic). Applying sum_to_zero_vector[2] b sets \(b = (u/\sqrt{2},\, -u/\sqrt{2})^\top\) for a single unconstrained scalar \(u \in \mathbb{R}\). Suppose the two group means \(\eta_1 = \alpha + b_1\) and \(\eta_2 = \alpha + b_2\) enter the likelihood with group precisions \(\kappa_1 = n_1 / \sigma^2\) and \(\kappa_2 = n_2 / \sigma^2\), with priors \(\alpha \sim \mathcal{N}(0, \sigma_\alpha^2)\) and \(b_j \sim \mathcal{N}(0, \tau^2)\). The \(2 \times 2\) posterior precision matrix in \((\alpha, u)\) is

\[ P_{\mathrm{s2z}} = \begin{pmatrix} \kappa_1 + \kappa_2 + \sigma_\alpha^{-2} & \dfrac{\kappa_1 - \kappa_2}{\sqrt{2}} \\[8pt] \dfrac{\kappa_1 - \kappa_2}{\sqrt{2}} & \dfrac{\kappa_1 + \kappa_2}{2} + \tau^{-2} \end{pmatrix}. \]

When the two groups have balanced information (\(\kappa_1 = \kappa_2\)), the off-diagonal \((\kappa_1 - \kappa_2)/\sqrt{2}\) vanishes and sum_to_zero_vector[2] is orthogonal. When group information is imbalanced (\(\kappa_1 \gg \kappa_2\)) and priors are weakly informative, the off-diagonal scales like \(\kappa_1 / \sqrt{2}\), the determinant collapses toward \(\kappa_1(2\kappa_2 + \tau^{-2})\), and the posterior correlation approaches

\[ |\operatorname{Corr}_{\mathrm{s2z}}(\alpha, u)| \approx \frac{|\kappa_1 - \kappa_2|}{\sqrt{(\kappa_1 + \kappa_2)(\kappa_1 + \kappa_2 + 2\tau^{-2})}} \xrightarrow{\kappa_1 \gg \kappa_2,\, \tau \text{ large}} 1. \]

Symmetric centering forces the data-rich group \(\eta_1 = \alpha + u/\sqrt{2}\) to share half of the noisy contrast’s variance, locking \(\alpha\) and \(u\) onto the diagonal line \(\alpha + u/\sqrt{2} \approx \bar{y}_1\).

Now replace \((\alpha, b)\) with a reference-relative pair: anchor \(\eta_{\mathrm{ref}} = \alpha + b_1\) on the higher-precision group and define the difference \(\delta = b_2 - b_1\), reconstructing \(\alpha = \eta_{\mathrm{ref}} + \tfrac{1}{2}\delta\) and \(b = (-\tfrac{1}{2}\delta,\, \tfrac{1}{2}\delta)^\top\). In \((\eta_{\mathrm{ref}}, \delta)\), the likelihood quadratic form is \(\kappa_1 \eta_{\mathrm{ref}}^2 + \kappa_2(\eta_{\mathrm{ref}} + \delta)^2\), giving posterior precision

\[ P_{\mathrm{rel}} = \begin{pmatrix} \kappa_1 + \kappa_2 + \sigma_\alpha^{-2} & \kappa_2 + \tfrac{1}{2}\sigma_\alpha^{-2} \\[6pt] \kappa_2 + \tfrac{1}{2}\sigma_\alpha^{-2} & \kappa_2 + \tfrac{1}{2}\tau^{-2} + \tfrac{1}{4}\sigma_\alpha^{-2} \end{pmatrix}. \]

As \(\kappa_1 \gg \kappa_2\), the upper-left entry grows as \(\kappa_1\) while the off-diagonal stays bounded by \(\kappa_2 + \tfrac{1}{2}\sigma_\alpha^{-2}\), driving \(|\operatorname{Corr}(\eta_{\mathrm{ref}}, \delta)| = O\bigl(\sqrt{\kappa_2 / \kappa_1}\bigr) \to 0\) and \(\max \rho \to 1\). Accordingly, diagnose recommends sum_to_zero_vector only for \(J \ge 3\) and routes both \(J = 2\) hierarchies and explicit sum_to_zero_vector[2] declarations with \(\rho > 1.3\) to relative_pair_reparam.

Code
j2 <- read.csv("advisor-j2-curve.csv", stringsAsFactors = FALSE)
j2_long <- rbind(
  data.frame(ratio = j2$precision_ratio, scheme = "sum_to_zero_vector[2] (symmetric)", corr = j2$corr_s2z2),
  data.frame(ratio = j2$precision_ratio, scheme = "Reference-relative (eta_ref, delta)", corr = j2$corr_relative)
)
j2_long$scheme <- factor(
  j2_long$scheme,
  levels = c("sum_to_zero_vector[2] (symmetric)", "Reference-relative (eta_ref, delta)")
)

p_j2 <- ggplot(j2_long, aes(x = ratio, y = corr, color = scheme, shape = scheme)) +
  geom_vline(xintercept = 3.0, linetype = "dotted", color = blog_colors$text_light, linewidth = 0.5) +
  geom_line(linewidth = 0.95) +
  geom_point(size = 2.6) +
  scale_x_log10(
    breaks = c(1, 2, 4, 8, 16, 32, 64, 100),
    labels = c("1", "2", "4", "8", "16", "32", "64", "100")
  ) +
  scale_y_continuous(limits = c(0, 1.04), breaks = seq(0, 1, 0.2)) +
  scale_color_manual(
    values = c(
      "sum_to_zero_vector[2] (symmetric)" = blog_colors$red,
      "Reference-relative (eta_ref, delta)" = blog_colors$teal
    ),
    name = NULL
  ) +
  scale_shape_manual(
    values = c(
      "sum_to_zero_vector[2] (symmetric)" = 16,
      "Reference-relative (eta_ref, delta)" = 17
    ),
    name = NULL
  ) +
  annotate("text", x = 3.3, y = 0.94, label = "Crossover (~3:1)", hjust = 0, size = 3.1, color = blog_colors$text_light) +
  guides(color = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  labs(
    title = "J = 2 Imbalance: s2z[2] vs. Relative",
    subtitle = "Intercept-contrast |Corr| vs. kappa_1 / kappa_2",
    x = "Group precision ratio kappa_1 / kappa_2 [log scale]",
    y = "Posterior |Corr|"
  )

ad <- read.csv("advisor-diagnostics.csv", stringsAsFactors = FALSE)

p_cal <- ggplot(ad, aes(x = n_per_group)) +
  geom_hline(yintercept = c(0.25, 0.75), linetype = "dashed", color = blog_colors$text_light, linewidth = 0.4) +
  geom_line(aes(y = lambda_exact, color = "Exact Fisher curve tau^2 / (tau^2 + sigma^2 / n_j)"), linewidth = 0.95) +
  geom_point(aes(y = lambda_advisor, color = "weftmc.diagnose() empirical estimate"), size = 3.0, shape = 17) +
  scale_x_continuous(
    trans = "log2",
    breaks = c(1, 2, 4, 8, 16, 32, 64, 128),
    labels = c("1", "2", "4", "8", "16", "32", "64", "128")
  ) +
  scale_y_continuous(limits = c(0, 1.04), breaks = seq(0, 1, 0.25)) +
  scale_color_manual(
    values = c(
      "Exact Fisher curve tau^2 / (tau^2 + sigma^2 / n_j)" = blog_colors$blue,
      "weftmc.diagnose() empirical estimate" = blog_colors$teal
    ),
    name = NULL
  ) +
  guides(color = guide_legend(nrow = 2)) +
  annotate("text", x = 1.05, y = 0.13, label = "Non-centered optimal", hjust = 0, size = 3.0, color = blog_colors$text_light) +
  annotate("text", x = 1.05, y = 0.50, label = "Partial centering", hjust = 0, size = 3.0, color = blog_colors$text_light) +
  annotate("text", x = 1.05, y = 0.88, label = "Centered + s2z optimal", hjust = 0, size = 3.0, color = blog_colors$text_light) +
  labs(
    title = "Partial-Centering Weight Calibration",
    subtitle = "Stein-IV conditional scales vs. exact Fisher curve",
    x = "Observations per group n_j [log2 scale]",
    y = "Centering weight lambda_g"
  )

(p_j2 + p_cal) &
  theme(
    legend.position = "bottom",
    legend.text = element_text(size = 9.0),
    plot.title = element_text(size = 13)
  )
Figure 3: Analytical verification of WeftMC’s structural diagnostics. Left: posterior correlation |Corr| between intercept and contrast for a J = 2 hierarchy across group precision ratios kappa_1 / kappa_2 from 1 to 100. sum_to_zero_vector[2] is orthogonal at balanced precision (kappa_1 = kappa_2) and degenerates toward |Corr| -> 1 under imbalance, crossing the reference-relative parameterization near kappa_1 / kappa_2 = 3. Right: empirical partial-centering weights lambda_g estimated by weftmc.diagnose() (points) vs. exact analytical Fisher weights tau^2 / (tau^2 + sigma^2 / n_j) (curve) across group sample sizes n_j = 1 to 128.

3.4 Empirical Partial-Centering Weights \(\hat{\lambda}_g\)

In the partial-centering framework of Papaspiliopoulos, Roberts, and Sköld (Papaspiliopoulos et al. 2007) and Post 13, a hierarchical vector \(\theta_j = \mu + \tau z_j\) with prior \(z_j \sim \mathcal{N}(0, 1)\) and group likelihood precision \(\kappa_j = n_j / \sigma^2\) has optimal centering weight \(\lambda_j^\star = \tau^2 \kappa_j / (1 + \tau^2 \kappa_j) \in (0, 1)\). Computing \(\lambda_j^\star\) analytically would require knowing how each group enters the likelihood.

Instead, diagnose reads \(\lambda_g\) straight off the conditional scales \(\sigma_{\mathrm{cond}, i} = \|B_0^{-1} e_i\|_2^{-1}\) of a non-centered standard-normal block \(z_g\): holding \((\mu, \tau, \sigma)\) fixed, the conditional posterior precision of \(z_i\) is \(1 + \tau^2 \kappa_i = \sigma_{\mathrm{cond}, i}^{-2}\), so \(1 - \sigma_{\mathrm{cond}, i}^2 / \sigma_{\mathrm{prior}, i}^2 = \tau^2 \kappa_i / (1 + \tau^2 \kappa_i) = \lambda_i^\star\) identically. Taking the block median gives

\[ \hat{\lambda}_g = \operatorname{clip}\!\left(1 - \operatorname{med}_{i \in g}\!\left(\frac{\sigma_{\mathrm{cond}, i}^2}{\sigma_{\mathrm{prior}, i}^2}\right),\, 0,\, 1\right), \]

classifying \(\hat{\lambda}_g < 0.25\) as non_centered_optimal, \(0.25 \le \hat{\lambda}_g \le 0.75\) as partial_centering_recommended, and \(\hat{\lambda}_g > 0.75\) as centered_or_s2z_recommended. The right panel of Figure 3 compares \(\hat{\lambda}_g\) from diagnose() against exact Fisher weights across \(n_j \in \{1, 2, 4, 8, 16, 32, 64, 128\}\) (\(\tau = 0.5\), \(\sigma = 1\)): the largest discrepancy across all eight sample sizes is \(0.0065\).

3.5 Four-Point Constraint Probing and Rate / Boundary Lever Arms

To detect nonlinear link couplings without relying on regexes alone, probe_stan_constraints evaluates param_constrain(z, include_tp=False, include_gq=False) at four constant vectors \(z \in \{\mathbf{0},\, \mathbf{1},\, -\mathbf{1},\, 2\mathbf{1}\}\) and classifies each scalar parameter algebraically:

  • identity: \(c(0) = 0\), \(c(1) = 1\), \(c(-1) = -1\), \(c(2) = 2\).
  • exp (real<lower=0>): \(c(0) = 1\), \(c(1)/c(0) = e\), \(c(2)/c(1) = e\).
  • lower_bound (real<lower=L>): \(c(z) - L = e^z\), giving \(L = c(0) - 1\).
  • upper_bound (real<upper=U>): \(U - c(z) = e^z\), giving \(U = c(0) + 1\).
  • logit (real<lower=L, upper=U>): symmetric midpoint \(m = \tfrac{1}{2}(c(1) + c(-1)) = c(0)\) and span \(U - L = (c(1) - c(-1)) / (2\sigma(1) - 1)\).

Combining those constraint classes with the Stein-IV correlation matrix catches two domain-level pathologies common in differential-equation and pharmacokinetic models:

  1. Difference-rate ridges (difference_rate_softplus). When two positive exp-constrained scalars \((\beta, \gamma)\) have marginal correlation \(\operatorname{Corr}(\log\beta, \log\gamma) \ge 0.75\), observations identify the net rate \(r = \beta - \gamma\) much tighter than either rate individually. diagnose flags the pair for softplus net-rate reparameterization \(\beta = \gamma + \operatorname{softplus}(\phi_r)\).

  2. Initial-value boundary lever arms (boundary_lever_arm). When a logit-bounded state \(I_0 \in (L, U)\) sits near its boundary and correlates strongly (\(|\operatorname{Corr}| \ge 0.65\)) with a positive growth rate, backward extrapolation from observation times \(t > 0\) to \(t = 0\) creates a lever arm \(u_{I_0}(0) \approx u_{I_0}(t_{\mathrm{ref}}) - r\,t_{\mathrm{ref}}\). diagnose estimates the empirical anchor time directly from the unconstrained Stein-IV covariance:

    \[ \widehat{\Delta t}_{\mathrm{ref}} = -\frac{\operatorname{Cov}(u_{I_0}, u_{\beta})}{\operatorname{Var}(u_{\beta})}. \]


4. How weftmc.reparameterize_stan Automatically Rewrites Stan Programs

Diagnosing a bad parameterization still leaves manual algebra—and manual Jacobian bugs—if the user has to edit the Stan file by hand. Earlier automatic reparameterizers such as VIP-Stan / Gorinova, Moore, and Hoffman (Gorinova et al. 2020) learned continuous variational centering weights over directed graphical models in custom probabilistic languages. weftmc.reparameterize_stan (reparam.py) solves a more constrained engineering problem: take an arbitrary Stan 2.36+ .stan file (optionally paired with a PosteriorInsights report from diagnose), emit a drop-in .stan file whose model block is untouched, preserve every original parameter name in transformed parameters for downstream posterior summaries, and guarantee exact target densities via jacobian +=.

4.1 Block-Level Architecture and Safety Guards

reparameterize_stan parses top-level Stan blocks (functions, data, transformed data, parameters, transformed parameters, model, generated quantities) with a brace-matching scanner after masking // and /* ... */ comments via strip_stan_comments (which replaces comment characters with spaces of identical byte length so character offsets into the original source stay exact and commented-out priors never fire rules).

Each transformation rule produces three edits:

  1. Replace the original declaration in parameters with unconstrained or orthogonalized latent coordinates.
  2. Insert the forward reconstruction of the exact original variable name and type at the top of transformed parameters (creating the block if absent), ordered by dependency stage (stage 0: scalar prior maps; stage 1: hierarchical hypermeans and group vectors that read stage-0 scales; stage 2: coupled rate or ODE maps), followed immediately by jacobian += ...;.
  3. Leave model and generated quantities byte-for-byte identical.

Because Stan 2.36+ evaluates jacobian += statements inside transformed parameters when sampling or optimizing—and omits them during log_prob(..., jacobian=false) MLE calls—every sampling statement in model (theta ~ normal(mu, tau);, y ~ normal(theta, sigma);, user-defined ODE calls) evaluates on the reconstructed constrained variables with the exact change-of-variables log-determinant.

Three safety guards prevent rewrites that degrade geometry on already well-parameterized models:

  • Double non-centering guard. Before rewriting a scale parameter \(\tau\), reparam.py scans transformed parameters and model for manual non-centering expressions such as mu + tau * eta or tau * z. If the user has already non-centered the hierarchy manually, applying a bounded tangent transform to tau is skipped so tau is not warped twice.
  • Lognormal scale-prior guard. When theta ~ normal(mu, tau) has tau ~ lognormal(m, s), the prior density on \(\tau\) vanishes smoothly as \(\tau \to 0^+\) rather than spiking to a nonzero constant at zero like half-normal, exponential, or half-Cauchy priors. Blindly non-centering informative data-dominated lognormal hierarchies creates an inverse-funnel ridge. Without insights, reparameterize_stan leaves lognormal-scaled hierarchies alone unless theta is a sum_to_zero_vector; with --guided (insights supplied), it rewrites only if diagnose confirms \(\hat{\lambda}_g < 0.85\) or \(\hat{k} > 0.5\).
  • Advisor-calibrated partial centering. When insights provides an empirical centering weight \(\hat{\lambda}_g \in (0.05, 0.95)\) for block theta, partial_centered_s2z sets the precision offset \(\tau_g = \hat{\lambda}_g / (1 - \hat{\lambda}_g)\) directly in the generated Stan code rather than defaulting to pure non-centering (\(\tau_g = 0\)).

4.2 Catalog of Automatic Transformations and Exact jacobian += Terms

1. Scale, Precision, Tail, and Shape-Rate Orthogonalization Rules

  • Overflow-safe exponential inverse-CDF (uncentered_exponential_icdf). For real<lower=0> tau with tau ~ exponential(r), Stan’s default \(\tau = e^u\) transform puts a sharp asymmetric double-exponential left tail \(p(u) = r \exp(u - r e^u)\) on \(u\). Writing real<lower=0, upper=1> u; tau = -log(u)/r avoids the exponential tail, except that extreme unconstrained draws round \(u \to 1.0\) in IEEE-754 float64 and collapse \(\tau\) to exact zero. Parameterizing \(u = \sigma(z_\tau) = (1 + e^{-z_\tau})^{-1}\) analytically gives \(-\log \sigma(z_\tau) = \log(1 + e^{-z_\tau}) = \operatorname{softplus}(-z_\tau)\):

    \[ \tau(z_\tau) = \frac{\operatorname{log1p\_exp}(-z_\tau)}{r}, \qquad \log\left|\frac{d\tau}{dz_\tau}\right| = \operatorname{log\_inv\_logit}(-z_\tau) - \log r, \]

    which pulls \(\operatorname{Exponential}(r)\) back to a smooth, log-concave \(\operatorname{Logistic}(0, 1)\) density on \(z_\tau \in \mathbb{R}\) with zero float64 underflow across the real line.

  • Bounded half-Cauchy tangent map (cauchy_tan_reparam). For real<lower=0> tau with tau ~ cauchy(0, s), polynomial right tails in \(\tau\) produce \(\hat{k} > 0.5\) under any Gaussian approximation on \(\log\tau\). Applying the inverse-CDF tangent map (Carpenter et al. 2017)

    \[ u_\tau \in \left(0, \frac{\pi}{2}\right), \qquad \tau(u_\tau) = s \tan(u_\tau), \qquad \log\left|\frac{d\tau}{du_\tau}\right| = \log s - 2\log\cos(u_\tau) \]

    cancels the Cauchy kernel \((1 + \tau^2/s^2)^{-1}\) against \(\sec^2(u_\tau)\), making the induced prior on \(u_\tau\) uniform on \((0, \pi/2)\).

  • Inverse-gamma moderated softplus precision (inv_gamma_softplus_precision). For real<lower=0> sigma2 with sigma2 ~ inv_gamma(a, b), right-skewness in \(\sigma^2\) and log-space asymmetry near the mode are compressed by mapping \(z \in \mathbb{R}\) through a unit-anchored softplus-squared precision \(\tilde{\tau}(z) = (\log 2)^{-2} \operatorname{log1p\_exp}(-0.55 z)^2\) and setting \(\sigma^2 = (b / a) / \tilde{\tau}(z)\).

  • Cox–Reid Gamma shape-mean orthogonalization (gamma_shape_mean_orthogonal). When observations follow y ~ gamma(alpha, beta) in shape-rate parameterization, the Fisher information matrix between \((\alpha, \beta)\) has off-diagonal \(N / \beta\), creating a curved banana ridge. By Cox and Reid (Cox and Reid 1987), replacing the rate \(\beta\) with the mean \(\mu_\beta = \alpha / \beta\) sets the off-diagonal Fisher information \(\mathcal{I}_{\alpha, \mu_\beta} = 0\):

    \[ \beta(\alpha, \mu_\beta) = \frac{\alpha}{\mu_\beta}, \qquad \log\left|\frac{\partial \beta}{\partial \mu_\beta}\right| = \log \alpha - 2\log \mu_\beta. \]

  • Truncated-normal quantile map (truncated_normal_quantile). When a bounded scalar real<lower=L, upper=U> x has prior x ~ normal(m, s) that places non-negligible mass against the bounds, reparam.py maps \(u_x \in (0, 1)\) through the truncated-normal inverse CDF \(x = m + s\,\Phi^{-1}\!\bigl(\Phi(a) + u_x[\Phi(b) - \Phi(a)]\bigr)\) where \(a = (L - m)/s\) and \(b = (U - m)/s\), so the induced prior on \(u_x\) is exactly \(\operatorname{Uniform}(0, 1)\).

Here is the verbatim output of reparameterize_stan on a shape-rate Gamma model (alpha ~ exponential(0.5); beta ~ exponential(0.5); y ~ gamma(alpha, beta);), showing how stage-0 uncentered_exponential_icdf feeds directly into gamma_shape_mean_orthogonal while model stays untouched:

data {
  int<lower=1> N;
  vector<lower=0>[N] y;
}
parameters {
  real z_alpha;
  real<lower=0> mu_beta;
}
transformed parameters {
  real<lower=0> alpha = log1p_exp(-z_alpha) / (0.5);
  jacobian += log_inv_logit(-z_alpha) - log(0.5);
  real<lower=0> beta = alpha / mu_beta;
  jacobian += log(alpha) - 2 * log(mu_beta);
}
model {
  alpha ~ exponential(0.5);
  beta ~ exponential(0.5);
  y ~ gamma(alpha, beta);
}

2. Hierarchical Sum-to-Zero Splitting, Conjugate Hypermeans, and \(J = 2\) Reference Pairs

  • Orthogonal group-mean / s2z split and conjugate hypermean (partial_centered_s2z, conjugate_hypermean). Consider a centered hierarchical block vector[J] theta ~ normal(mu, tau) with normal hyperprior mu ~ normal(m0, s0). Marginalizing \(\mu\) out of the joint prior \((\mu, \theta) \mid \tau\) decomposes \(\theta\) into two prior-independent pieces: its sample mean \(\bar{\theta} = \frac{1}{J}\sum_{j=1}^J \theta_j \sim \mathcal{N}(m_0,\, s_0^2 + \tau^2 / J)\) and its sum-to-zero within-group deviations \(\theta - \bar{\theta}\mathbf{1}_J\), while the conditional prior of the hypermean given \(\bar{\theta}\) is normal with variance \(v_\mu = s_0^2 \tau^2 / (\tau^2 + J s_0^2)\) and mean \(m_\mu = (\tau^2 m_0 + J s_0^2 \bar{\theta}) / (\tau^2 + J s_0^2)\).

    Introducing real z_bar_theta, sum_to_zero_vector[J] z_subj_theta (with partial-centering scale \(s_{\mathrm{sub}} = \tau / \sqrt{1 + \tau_g \tau^2}\)), and real z_mu_mu eliminates both the \(\tau \to 0\) centered funnel and the \(\mu \leftrightarrow \bar{\theta}\) translation ridge simultaneously. Because the orthogonal transformation from \((\bar{\theta},\, z_{\mathrm{s2z}})\) on the zero-sum hyperplane to \(\theta \in \mathbb{R}^J\) has volume factor \(\sqrt{J}\), the exact log-determinant of \((\bar{z}, z_{\mathrm{subj}}, z_\mu) \mapsto (\theta, \mu)\) at fixed \(\tau\) is

    \[ \log|\det J| = \frac{1}{2}\log J + \log s_{\mathrm{bar}} + (J - 1)\log s_{\mathrm{sub}} + \frac{1}{2}\log v_\mu. \]

    Running reparameterize_stan on classic centered Eight Schools (eight_schools_centered.stan) produces this complete Stan program automatically:

data {
  int<lower=0> J;
  vector[J] y;
  vector<lower=0>[J] sigma;
}
parameters {
  real z_mu_mu;
  real<lower=0, upper=0.5 * pi()> u_tau;
  real z_bar_theta;
  sum_to_zero_vector[J] z_subj_theta;
}
transformed parameters {
  real<lower=0> tau = (5) * tan(u_tau);
  jacobian += log(5) - 2 * log(cos(u_tau));
  vector[J] theta;
  real mu;
  {
    real sig_weft = tau;
    real s0_sq_weft = square(5);
    real sig_sq_weft = square(sig_weft);
    real s_bar_weft = sqrt(s0_sq_weft + sig_sq_weft / (J));
    real s_sub_weft = sig_weft / sqrt(1.0 + 0.0 * sig_sq_weft);
    real bar_weft = (0) + s_bar_weft * z_bar_theta;
    theta = bar_weft + s_sub_weft * z_subj_theta;
    real denom_weft = sig_sq_weft + (J) * s0_sq_weft;
    real v_mu_weft = (s0_sq_weft * sig_sq_weft) / denom_weft;
    real m_mu_weft = (sig_sq_weft * (0) + (J) * s0_sq_weft * bar_weft) / denom_weft;
    mu = m_mu_weft + sqrt(v_mu_weft) * z_mu_mu;
    jacobian += 0.5 * log(J) + log(s_bar_weft) + ((J) - 1) * log(s_sub_weft) + 0.5 * log(v_mu_weft);
  }
}
model {
  mu ~ normal(0, 5);
  tau ~ cauchy(0, 5);
  theta ~ normal(mu, tau);
  y ~ normal(theta, sigma);
}
  • \(J = 2\) reference-relative contrast (relative_pair_reparam). For either a 2-level hierarchy vector[2] b ~ normal(alpha, tau) or an explicit sum_to_zero_vector[2] b paired with scalar intercept alpha, reparam.py replaces (alpha, b) with (eta_ref_alpha, delta_b). In the sum_to_zero_vector[2] case, Stan’s built-in isometric basis maps its single unconstrained coordinate \(u\) to \((u/\sqrt{2}, -u/\sqrt{2})^\top\), whereas \((\eta_{\mathrm{ref}}, \delta) \mapsto (\eta_{\mathrm{ref}} + \tfrac{1}{2}\delta,\, -\tfrac{1}{2}\delta)\) maps to \((\alpha, u = -\delta/\sqrt{2})\) with constant Jacobian \(1/\sqrt{2}\), yielding jacobian += -0.5 * log2():
parameters {
  real eta_ref_alpha;
  real<lower=0> tau;
  real delta_b;
}
transformed parameters {
  real alpha = eta_ref_alpha + 0.5 * delta_b;
  vector[2] b = [-0.5 * delta_b, 0.5 * delta_b]';
  jacobian += -0.5 * log2();
}

3. Coupled ODE and Pharmacokinetic Rate Rules

  • SIR net-growth and reference-time anchor (sir_growth_anchor). When a susceptible-infectious-recovered ODE declares \((\beta, \gamma, i_0)\) (real<lower=0> beta, gamma; real<lower=0, upper=1> i0;), reparam.py replaces beta with unconstrained phi_r so \(r = \operatorname{softplus}(\phi_r)\) and \(\beta = \gamma + r\) (\(\log|\partial\beta/\partial\phi_r| = \operatorname{log\_inv\_logit}(\phi_r)\)), and shifts logit(i0) by \(-r\,t_{\mathrm{ref}}\) (t_ref = 2.5 by default or calibrated from insights), decoupling early exponential growth from initial prevalence.
  • Michaelis–Menten intrinsic clearance (michaelis_menten_clearance). In saturable elimination models where concentration stays near or below \(K_m\), \(V_m\) and \(K_m\) trade off along their ratio \(CL_{\mathrm{int}} = V_m / K_m\). Replacing V_m with CL_int and reconstructing V_m = CL_int * K_m adds jacobian += log(K_m) and breaks the hyperbolic ridge.

4.3 Exact Jacobian Verification and Nine-Model Benchmark Suite

Every rule in reparam.py is tested numerically before benchmarking. For each model, we draw random points \(z^{(m)} \in \mathbb{R}^d\) in the rewritten unconstrained space, map each \(z^{(m)}\) through the rewritten model’s param_constrain(..., include_tp=True) to recover the reconstructed original parameters, pull those back to the original model’s unconstrained coordinates \(x^{(m)}\), and compare the induced densities including finite-difference log-Jacobians \(\log|\det \partial x / \partial z|\). If the Stan jacobian += term is exact, the difference \(\Delta_m = \log p_{\mathrm{rewritten}}(z^{(m)}) - \bigl[\log p_{\mathrm{orig}}(x^{(m)}) + \log|\det \partial x/\partial z(z^{(m)})|\bigr]\) is constant across all \(z^{(m)}\) up to floating-point rounding. Across all nine models in Table 3, the peak-to-peak discrepancy (Jacobian ptp) lies between \(1.22 \times 10^{-10}\) and \(1.05 \times 10^{-9}\).

Code
rb <- read.csv("reparam-benchmarks.csv", stringsAsFactors = FALSE)
rb <- rb[order(rb$speedup_x), ]
rb$model_f <- factor(rb$model, levels = rb$model)

rb$k_orig_plot <- ifelse(is.infinite(rb$k_hat_orig), 2.60, rb$k_hat_orig)

rb_k_long <- rbind(
  data.frame(model_f = rb$model_f, state = "Original .stan", k_val = rb$k_orig_plot),
  data.frame(model_f = rb$model_f, state = "After reparameterize_stan()", k_val = rb$k_hat_reparam)
)
rb_k_long$state <- factor(rb_k_long$state, levels = c("Original .stan", "After reparameterize_stan()"))

p_khat <- ggplot() +
  geom_vline(xintercept = 0.5, linetype = "dashed", color = blog_colors$text_light, linewidth = 0.5) +
  geom_segment(
    data = rb,
    aes(x = k_orig_plot, xend = k_hat_reparam, y = model_f, yend = model_f),
    color = blog_colors$blue,
    linewidth = 0.8
  ) +
  geom_point(
    data = rb_k_long,
    aes(x = k_val, y = model_f, color = state, shape = state),
    size = 3.0
  ) +
  geom_text(
    data = subset(rb, is.infinite(k_hat_orig)),
    aes(x = 2.60, y = model_f, label = "Inf"),
    nudge_x = 0.22,
    size = 3.0,
    color = blog_colors$red,
    fontface = "bold"
  ) +
  scale_color_manual(
    values = c(
      "Original .stan" = blog_colors$red,
      "After reparameterize_stan()" = blog_colors$teal
    ),
    name = NULL
  ) +
  scale_shape_manual(
    values = c(
      "Original .stan" = 16,
      "After reparameterize_stan()" = 17
    ),
    name = NULL
  ) +
  scale_x_continuous(limits = c(-1.95, 3.05), breaks = c(-1.5, -0.5, 0, 0.5, 1.5, 2.5)) +
  annotate("text", x = 0.44, y = 1.35, label = "k_hat = 0.5", hjust = 1, size = 3.0, color = blog_colors$text_light) +
  labs(
    title = "Variational Tail Shape (PSIS k_hat)",
    subtitle = "Pure Stein-IV fit before and after source rewrite",
    x = "Stein-IV PSIS k_hat",
    y = NULL
  )

rb$bar_dir <- ifelse(rb$speedup_x >= 1.0, "Faster (>= 1x)", "Slower (< 1x)")
rb$lbl_speed <- ifelse(
  rb$speedup_x >= 100,
  sprintf("%.0fx", rb$speedup_x),
  sprintf("%.2fx", rb$speedup_x)
)

p_ess <- ggplot(rb, aes(x = speedup_x, y = model_f, fill = bar_dir)) +
  geom_vline(xintercept = 1.0, linetype = "dashed", color = blog_colors$text_light, linewidth = 0.5) +
  geom_col(width = 0.62) +
  geom_text(
    aes(
      label = lbl_speed,
      hjust = ifelse(speedup_x >= 1.0, -0.15, 1.15)
    ),
    size = 3.1,
    color = blog_colors$text,
    fontface = "bold"
  ) +
  scale_x_log10(
    limits = c(0.28, 11000),
    breaks = c(0.3, 1, 10, 100, 1000),
    labels = c("0.3x", "1x", "10x", "100x", "1,000x")
  ) +
  scale_fill_manual(
    values = c(
      "Faster (>= 1x)" = blog_colors$teal,
      "Slower (< 1x)" = blog_colors$gold
    ),
    guide = "none"
  ) +
  labs(
    title = "4-Chain MCMC Throughput Gain",
    subtitle = "weftmc.sample ESS/s ratio (rewritten / original)",
    x = "ESS/s speedup factor [log10]",
    y = NULL
  ) +
  theme(axis.text.y = element_blank(), axis.ticks.y = element_blank())

(p_khat + p_ess) +
  plot_layout(widths = c(1.15, 1.0), guides = "collect") &
  theme(legend.position = "bottom", legend.text = element_text(size = 9.5))
Figure 4: Impact of automatic source rewriting (weftmc.reparameterize_stan) across nine Stan models. Left: pure Stein-IV PSIS k_hat before and after rewriting (arma11’s divergent k_hat = Inf is plotted at 2.6). Rewriting pulls five previously failing models below the k_hat = 0.5 threshold where density-only variational MTM and zero-overhead VI operate. Right: 4-chain weftmc.sample effective sample size per second (ESS/s) speedup ratio after / before on a log10 scale.
Code
rb_tab <- read.csv("reparam-benchmarks.csv", stringsAsFactors = FALSE)
rb_tab <- rb_tab[order(-rb_tab$speedup_x), ]

fmt_rho <- function(v) {
  ifelse(v > 1e4, sprintf("%.1e", v), sprintf("%.2f", v))
}

fmt_k <- function(v) {
  ifelse(is.infinite(v), "Inf", sprintf("%+.2f", v))
}

disp_rb <- data.frame(
  Model = rb_tab$model,
  d = rb_tab$dim,
  `Applied Rules` = rb_tab$rules,
  `Jac ptp` = sprintf("%.2e", rb_tab$jacobian_ptp),
  `k_hat (Orig -> New)` = paste0(fmt_k(rb_tab$k_hat_orig), " -> ", fmt_k(rb_tab$k_hat_reparam)),
  `Max rho (Orig -> New)` = paste0(fmt_rho(rb_tab$max_rho_orig), " -> ", fmt_rho(rb_tab$max_rho_reparam)),
  `ESS/s (Orig -> New)` = sprintf("%.1f -> %.1f", rb_tab$ess_per_s_orig, rb_tab$ess_per_s_reparam),
  `Speedup` = ifelse(rb_tab$speedup_x >= 100, sprintf("%.0fx", rb_tab$speedup_x), sprintf("%.2fx", rb_tab$speedup_x)),
  check.names = FALSE
)

kable(disp_rb, row.names = FALSE, align = c("l", "r", "l", "r", "r", "r", "r", "r"))
Table 3: Exactness check (Jacobian peak-to-peak error), Stein-IV geometry before and after weftmc.reparameterize_stan, and 4-chain weftmc.sample ESS/s across nine Stan models.
Model d Applied Rules Jac ptp k_hat (Orig -> New) Max rho (Orig -> New) ESS/s (Orig -> New) Speedup
funnel 8 partial_centered_s2z 1.46e-10 +0.17 -> -1.75 1.00 -> 1.00 140.6 -> 410580.8 2921x
exp_hyperprior 11 uncentered_exponential_icdf + conjugate_hypermean 5.28e-10 +0.83 -> +0.68 1.43 -> 1.52 1309.5 -> 48701.9 37.19x
eight_schools_c 10 cauchy_tan_reparam + conjugate_hypermean 4.41e-10 +1.09 -> +0.30 3.0e+08 -> 1.08 1936.6 -> 27158.4 14.02x
sir_prepeak 3 sir_growth_anchor 1.05e-09 +2.28 -> +0.74 6.24 -> 8.49 5.2 -> 38.6 7.44x
gamma_shape_rate 2 gamma_shape_mean_orthogonal 1.41e-10 +0.40 -> -0.31 2.27 -> 1.08 224174.6 -> 298897.0 1.33x
s2z2_asymmetric 3 relative_pair_reparam 1.22e-10 +0.56 -> +0.13 1.53 -> 1.01 261012.7 -> 300117.2 1.15x
arK 7 cauchy_tan_reparam 6.50e-10 +1.21 -> +0.29 4.43 -> 4.31 15314.0 -> 16985.0 1.11x
arma11 4 cauchy_tan_reparam 6.57e-10 Inf -> +0.13 29.65 -> 1.03 27695.6 -> 28705.1 1.04x
cauchy_invchi2 2 cauchy_tan_reparam + inv_gamma_softplus_precision 2.20e-10 +0.76 -> +1.02 1.00 -> 1.17 123441.4 -> 93729.5 0.76x

Figure 4 and Table 3 summarize what source rewriting changes across nine representative Stan programs:

  • Centered funnels and exponential hyperpriors (funnel, exp_hyperprior, eight_schools_c). On Neal’s 8-dimensional funnel, non-centering via partial_centered_s2z drops \(\hat{k}\) from \(+0.17\) to \(-1.75\) and switches weftmc.sample from trajectory nuts (\(140.6\text{ ESS/s}\)) to density-only variational_mtm (\(410{,}580.8\text{ ESS/s}\), a \(2{,}921\times\) jump). On eight_schools_c, combining cauchy_tan_reparam and conjugate_hypermean eliminates the \(\max\rho = 3.0 \times 10^8\) centered funnel trap (\(\max\rho \to 1.08\), \(\hat{k}: +1.10 \to +0.30\)), raising 4-chain throughput \(14.02\times\). On exp_hyperprior, uncentered_exponential_icdf + conjugate_hypermean increases NUTS throughput \(37.19\times\) (\(1{,}309.5 \to 48{,}701.9\text{ ESS/s}\)).
  • Heavy-tailed time series, imbalanced \(J = 2\) pairs, and pre-peak ODEs (arma11, arK, s2z2_asymmetric, gamma_shape_rate, sir_prepeak). On arma11 and arK, cauchy_tan_reparam pulls \(\hat{k}\) from \(\infty\) and \(+1.21\) down to \(+0.13\) and \(+0.29\). On s2z2_asymmetric (\(n_1 = 64\), \(n_2 = 1\)), replacing sum_to_zero_vector[2] with relative_pair_reparam drops \(\hat{k}\) from \(+0.56\) to \(+0.13\) and \(\max\rho\) from \(1.53\) to \(1.01\). On sir_prepeak, sir_growth_anchor lowers \(\hat{k}\) from \(+2.28\) to \(+0.74\) and speeds up 4-chain ODE NUTS \(7.44\times\) (\(5.2 \to 38.6\text{ ESS/s}\)).
  • Where automatic prior rewriting adds slight overhead (cauchy_invchi2). On the 2-parameter cauchy_invchi2 model, sufficient statistics already dominate the Cauchy and inverse-gamma priors, so the original posterior is well-behaved without rewriting. Evaluating tan(u) and nested log1p_exp calls on every leapfrog step adds modest transcendental arithmetic, reducing throughput from \(123{,}441\text{ ESS/s}\) to \(93{,}730\text{ ESS/s}\) (\(0.76\times\)). That tradeoff is why --guided exists when diagnose() shows the original posterior already has \(\max\rho \approx 1\) and fast mixing.

5. Practical Workflow and Scope Boundaries

On the command line, the three modules compose into a short pre-flight and sampling sequence:

# 1. Fit the Stein-IV chart (refine=False) and print structural diagnostics (~20-500 ms)
weftmc vi model.stan --data data.json --insights

# 2. Rewrite parameters + transformed parameters with advisor-calibrated weights
weftmc reparam model.stan --data data.json --guided -o model_reparam.stan

# 3. Draw calibrated VI samples (PSIS-SIR if k_hat <= 0.5; 4-chain C++17 NUTS if k_hat > 0.5)
weftmc vi model_reparam.stan --data data.json --out vi_draws.json

# 4. Or run full independent-chain MCMC on the rewritten Stan model
weftmc sample model_reparam.stan --data data.json --chains 4 --draws 1000

The equivalent Python workflow inspects the PosteriorInsights object directly before writing the new .stan file:

from weftmc import StanTarget, diagnose, fit_vi, reparameterize_stan, sample

target = StanTarget("model.stan", data="data.json")
insights = diagnose(target, seed=42)
print(insights.summary())

rewritten = reparameterize_stan(
    "model.stan",
    insights=insights,
    output_path="model_reparam.stan",
)
reparam_target = StanTarget("model_reparam.stan", data="data.json")

vi_fit = fit_vi(reparam_target, seed=42)       # refine="auto" by default
mcmc_fit = sample(reparam_target, starts=4)    # 4 independent chains

Two boundaries still require manual modeling judgment. First, reparameterize_stan matches standard Stan declarations and sampling statements; when hierarchical priors are hidden inside custom C++/Stan functions blocks, ragged index slices, or multivariate Kronecker products (phylo_mv in Post 14), diagnose() will still surface the high \(\rho_j\) ratios and centering weights \(\hat{\lambda}_g\) from score geometry, while writing the custom sum_to_zero_constrain() or Cholesky partial-centering block remains manual (Post 13). Second, when a stiff nonlinear ODE model hits hard solver step-limit walls across most of \(\mathbb{R}^d\), short Stein-chart NUTS refinement (fit_vi) improves uncertainty substantially over static importance resampling while still carrying fewer effective draws than a full 4,000-draw MCMC run; checking vi_fit.psis_k_hat and split \(\widehat{R}\) on the refined chains tells you immediately when to step up to weftmc.sample.

Note

The variational algorithms, geometric diagnostics, automatic Stan reparameterization rules in WeftMC, and benchmark design are mine. Part of the C++17/Python implementation, benchmark scripts, and this post was developed with assistance from Antigravity.

References

Betancourt, Michael, and Mark Girolami. 2015. “Hamiltonian Monte Carlo for Hierarchical Models.” In Current Trends in Bayesian Methodology with Applications. Chapman; Hall/CRC.
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.
Carpenter, Bob, Andrew Gelman, Matthew D. Hoffman, et al. 2017. “Stan: A Probabilistic Programming Language.” Journal of Statistical Software 76 (1): 1–32. https://doi.org/10.18637/jss.v076.i01.
Cox, D. R., and N. Reid. 1987. “Parameter Orthogonality and Approximate Conditional Inference.” Journal of the Royal Statistical Society: Series B (Methodological) 49 (1): 1–18. https://doi.org/10.1111/j.2517-6161.1987.tb01422.x.
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.
Gorinova, Maria I., Dave Moore, and Matthew D. Hoffman. 2020. “Automatic Reparameterisation of Probabilistic Programs.” Proceedings of the 37th International Conference on Machine Learning, Proceedings of machine learning research, vol. 119: 3648–57.
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, Qiang, and Dilin Wang. 2016. “Stein Variational Gradient Descent: A General Purpose Bayesian Inference Algorithm.” Advances in Neural Information Processing Systems 29: 2378–86.
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.
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.
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.
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, 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, Lu, Bob Carpenter, Andrew Gelman, and Aki Vehtari. 2022. “Pathfinder: Parallel Quasi-Newton Variational Inference.” Journal of Machine Learning Research 23 (306): 1–49.