3. Hierarchical models¶
The eight-schools data (Rubin, 1981) give one estimated treatment effect \(y_j\) and its known standard error \(\sigma_j\) for each of eight schools. A hierarchical model draws the school effects from a shared population distribution, so each estimate is shrunk toward the population mean by an amount that depends on its standard error (partial pooling) (Gelman et al., 2013). Write the model in QVR with a plate over schools, fit it with stochastic variational inference (SVI) and with the No-U-Turn Sampler (NUTS) (Hoffman and Gelman, 2014), and compare the centered and non-centered parameterizations.
Eight schools, centered¶
Let \(\mu\) be the population mean, \(\tau\) the scale of the variation between schools, and \(\theta_j\) the effect of school \(j\):
object School : FinSet 8
program eight_schools_centered : School -> School [effects=[Sample, Score]]
let mu <- sample Normal(loc=0.0, scale=5.0)
let tau <- sample HalfNormal(scale=5.0)
let theta : School <- sample Normal(loc=mu, scale=tau)
observe y : School <- Normal(loc=theta, scale=sigma_j)
return theta
export eight_schools_centered
let theta : School <- sample Normal(...) is a plate: it draws one value for each of the eight elements of School, independently given mu and tau, and later let steps may index the result as theta[j]. observe y : School <- ... observes one value for each school in the same way. The standard errors sigma_j are a data input.
Centered parameterization and mean-field VI¶
In the centered form each \(\theta_j\) is drawn around \(\mu\) with scale \(\tau\). As \(\tau\) approaches zero, the conditional distribution of the \(\theta_j\) narrows, and the posterior of \((\theta, \tau)\) takes the shape of a funnel ((Neal, 2003), §8). A mean-field guide has no correlation between \(\theta\) and \(\tau\) and may place too much mass near \(\tau = 0\):
import torch
from quivers.dsl import loads
from quivers.inference import AutoNormalGuide, ELBO, SVI
CENTERED_SRC = """
object School : FinSet 8
program eight_schools_centered : School -> School
let mu <- sample Normal(loc=0.0, scale=5.0)
let tau <- sample HalfNormal(scale=5.0)
let theta : School <- sample Normal(loc=mu, scale=tau)
observe y : School <- Normal(loc=theta, scale=sigma_j)
return theta
export eight_schools_centered
"""
program = loads(CENTERED_SRC)
model = program.morphism
sigma_j = torch.tensor([[15., 10., 16., 11., 9., 11., 10., 18.]]) # (1, 8)
y_obs = torch.tensor([[28., 8., -3., 7., -1., 1., 18., 12.]]) # (1, 8)
guide = AutoNormalGuide(model, observed_names={"y", "sigma_j"})
elbo = ELBO(num_particles=1)
optimizer = torch.optim.Adam(
list(model.parameters()) + list(guide.parameters()), lr=1e-2,
)
svi = SVI(model, guide, optimizer, elbo)
x_tensor = torch.zeros(1, 1)
observations = {"sigma_j": sigma_j, "y": y_obs}
for _ in range(50): # bump to ~3000 for real fits
svi.step(x_tensor, observations)
To see the effect, fit both parameterizations from several initializations and compare the guide's distribution of tau with a well-mixed NUTS fit.
Non-centered parameterization¶
The non-centered form draws a standardized effect \(\eta_j \sim \mathrm{Normal}(0, 1)\) and sets \(\theta_j = \mu + \tau \eta_j\) deterministically (Papaspiliopoulos et al., 2007). The latent variables \(\eta_j\) are then independent of \(\tau\) a priori, and the funnel moves out of the sampled coordinates.
object School : FinSet 8
program eight_schools_noncentered : School -> School [effects=[Sample, Score]]
let mu <- sample Normal(loc=0.0, scale=5.0)
let tau <- sample HalfNormal(scale=5.0)
let eta : School <- sample Normal(loc=0.0, scale=1.0)
let theta = mu + tau * eta
observe y : School <- Normal(loc=theta, scale=sigma_j)
return theta
export eight_schools_noncentered
A mean-field guide often fits this form better. Whether it agrees with NUTS is a question for the diagnostics below.
NUTS¶
NUTS is a Hamiltonian Monte Carlo (HMC) sampler that chooses its trajectory length adaptively (Neal, 2011; Hoffman and Gelman, 2014):
from quivers.inference import NUTSKernel, MCMC
kernel = NUTSKernel(
target_accept=0.95, # high target -> smaller step -> fewer divergences
max_tree_depth=10,
)
# Small budget for documentation; bump warmup/samples for real fits.
mcmc = MCMC(
kernel,
num_warmup=50,
num_samples=100,
num_chains=2,
init_strategy="prior",
)
result = mcmc.run(model, x_tensor, {"sigma_j": sigma_j, "y": y_obs})
print("posterior mean tau:", result.samples["tau"].mean().item())
print("R-hat tau:", result.r_hat["tau"].item())
print("ESS tau:", result.ess["tau"].item())
print("divergences:", result.total_divergences)
result.r_hat is the rank-normalized split R-hat (Vehtari et al., 2021), which compares the variance between chains with the variance within them. result.ess is the effective sample size, and result.total_divergences counts trajectories whose numerical integration error blew up (Betancourt and Girolami, 2015). With 50 warmup steps and 100 draws, R-hat for tau is usually above 1.01 and its effective sample size is a few dozen at most. Thresholds and remedies are in chapter 8.
Centered or non-centered?¶
The better parameterization depends on how informative each group's likelihood is (Betancourt and Girolami, 2015; Stan Development Team, n.d.-a). The centered form tends to work when \(\sigma_j\) is small relative to \(\tau\), and the non-centered form when the group likelihoods are weak and the posterior narrows sharply as \(\tau\) approaches zero. In eight schools \(\sigma_j\) ranges from 9 to 18, while the prior puts substantial mass on values of \(\tau\) below 10, so the group likelihoods are weak. Compare divergences and effective sample sizes under both forms on the data at hand.
Initialization and mass matrix¶
init_strategy takes four values. "jitter" (the default) starts each chain at a small random point near the origin of the unconstrained space, that is, \(0.1\,z\) with \(z\) standard Normal. "prior", used above, draws every latent variable from its prior, running the model forward with the observed sites held at their values, and maps the draw into the unconstrained space. "zero" starts at the origin, and "guide" draws the starting point from a fitted guide passed to MCMC.run.
The mass matrix is the metric that HMC adapts during warmup to rescale the latent coordinates (Neal, 2011). NUTSKernel(mass_matrix="diagonal"), the default, adapts one variance for each coordinate. "dense" adapts a full covariance, which can help when latent variables are strongly correlated, at memory quadratic in their number. "identity" does not adapt.
Posterior predictive¶
Predictive accepts an MCMCResult as well as a Guide:
from quivers.inference import Predictive
pred = Predictive(model, posterior=result, num_samples=100)
y_hat = pred(x_tensor, {"sigma_j": sigma_j})["y"] # (100, ..., 8)
print("predictive school 1:", y_hat[..., 0].mean().item(),
"+/-", y_hat[..., 0].std().item())
Try this¶
- Fit the centered form with
AutoMultivariateNormalGuide, whose full covariance can represent part of the funnel's correlation. - Lower
target_acceptfrom 0.95 to 0.8 with longer warmup, and count divergences. A lower target gives a larger step size. - Add a covariate \(x_j\) for each school and give each school its own intercept and slope.
Next¶
Chapter 4 sums discrete latent variables out of mixtures with the marginalize block.
Cited sources¶
Donald B. Rubin. Estimation in Parallel Randomized Experiments. Journal of Educational Statistics, 6(4):377–401, 1981. URL: https://journals.sagepub.com/doi/10.3102/10769986006004377, doi:10.3102/10769986006004377.
Andrew Gelman, John B. Carlin, Hal S. Stern, David B. Dunson, Aki Vehtari, and Donald B. Rubin. Bayesian Data Analysis. Chapman and Hall/CRC, 3 edition, 2013. ISBN 9781439840955. URL: https://www.routledge.com/Bayesian-Data-Analysis/Gelman-Carlin-Stern-Dunson-Vehtari-Rubin/p/book/9781439840955.
Matthew D. Hoffman and Andrew Gelman. The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(47):1593–1623, 2014. URL: https://www.jmlr.org/papers/v15/hoffman14a.html.
Radford M. Neal. Slice sampling. The Annals of Statistics, 31(3):705–767, 2003. With discussion. URL: https://doi.org/10.1214/aos/1056562461, doi:10.1214/aos/1056562461.
Omiros Papaspiliopoulos, Gareth O. Roberts, and Martin Sköld. A General Framework for the Parametrization of Hierarchical Models. Statistical Science, 22(1):59–73, 2007. URL: https://projecteuclid.org/journals/statistical-science/volume-22/issue-1/A-General-Framework-for-the-Parametrization-of-Hierarchical-Models/10.1214/088342307000000014.pdf, doi:10.1214/088342307000000014.
Radford M. Neal. MCMC Using Hamiltonian Dynamics. In Steve Brooks, Andrew Gelman, Galin L. Jones, and Xiao-Li Meng, editors, Handbook of Markov Chain Monte Carlo, chapter 5, pages 113–162. Chapman and Hall/CRC, 2011. URL: https://doi.org/10.1201/b10905-6, doi:10.1201/b10905-6.
Aki Vehtari, Andrew Gelman, Daniel Simpson, Bob Carpenter, and Paul-Christian Bürkner. Rank-Normalization, Folding, and Localization: An Improved R-hat for Assessing Convergence of MCMC (with Discussion). Bayesian Analysis, 16(2):667–718, 2021. URL: https://doi.org/10.1214/20-BA1221, doi:10.1214/20-BA1221.
Michael Betancourt and Mark Girolami. Hamiltonian Monte Carlo for Hierarchical Models. In Satyanshu K. Upadhyay, Umesh Singh, Dipak K. Dey, and Appaia Loganathan, editors, Current Trends in Bayesian Methodology with Applications, pages 79–101. Chapman and Hall/CRC, 2015. URL: https://doi.org/10.1201/b18502-5, doi:10.1201/b18502-5.
Stan Development Team. Efficiency tuning. Stan User's Guide, version 2.40, n.d.-a. URL: https://mc-stan.org/docs/stan-users-guide/efficiency-tuning.html (visited on 2026-11-06).