Toy Model: Hierarchical Gaussian Model (HGM)¶
Step 1 - Define the generative model with Pyro¶
We define a three-level Hierarchical Gaussian Model (HGM):
- Global level: a latent variable \(z_2 \in \mathbb{R}^{\text{dim}}\) with prior \(z_2 \sim \mathcal{N}(0, I_{\text{dim}})\).
- Group level: \(N_{\text{groups}}\) latent variables \(z_1^i \in \mathbb{R}^{\text{dim}}\) (plate \(P_1\)), each conditionally distributed as \(z_1^i \mid z_2 \sim \mathcal{N}(z_2, \sigma_1^2 I_{\text{dim}})\).
- Observation level: \(N_{\text{obs}}\) observations \(X^{i,j} \in \mathbb{R}^{\text{dim}}\) per group (plate \(P_0\), nested in \(P_1\)), each conditionally distributed as \(X^{i,j} \mid z_1^i \sim \mathcal{N}(z_1^i, \sigma_0^2 I_{\text{dim}})\).
All variables share the same dimension \(\text{dim}\), so no projections are needed between levels. The scale parameters \(\sigma_1\) and \(\sigma_0\) are fixed hyperparameters set by the user.
In Pyro, plate \(P_1\) is mapped to the tensor dimension -1 and \(P_0\) to -2, so the observations have shape (num_observations, num_groups, dim). The model also accepts an optional idx argument (plate name → subsample indices): the PAVI guide calls the model as model(data, idx), and idx lets the plates be subsampled for mini-batch training.
import pyro
import pyro.distributions as dist
import torch
from pyro.nn import PyroModule
class ModelHGM(PyroModule):
"""
Simplified Hierarchical Gaussian Model (HGM) with three levels:
Level 1 (Global): z_2 ~ N(0, I_dim), dimension dim
Level 2 (Groups): z_1^i | z_2 ~ N(z_2, sigma_1^2 I_dim),
for i = 1, ..., num_groups (plate P_1)
Level 3 (Observed): X^{i,j} | z_1^i ~ N(z_1^i, sigma_0^2 I_dim),
for i = 1, ..., num_groups, j = 1, ..., num_observations (plate P_0)
All latent and observed variables share the same dimension (dim).
No projections between levels - each level directly depends on its parent.
Scale parameters sigma_1 and sigma_0 are fixed by the user (not learnable).
"""
def __init__(
self,
dim: int,
num_groups: int,
num_observations: int,
sigma_1: float,
sigma_0: float,
device: str | None = None,
):
super().__init__()
self.dim = dim
self.num_groups = num_groups
self.num_observations = num_observations
self.sigma_1 = sigma_1
self.sigma_0 = sigma_0
if device is not None:
self.device = device
else:
self.device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
def create_plates(
self,
data: torch.Tensor | None = None,
idx: dict | None = None,
) -> tuple[pyro.primitives.plate]:
"""Create plates for the hierarchical structure, optionally subsampled with `idx`."""
idx = idx if idx is not None else {}
plate_P_1 = pyro.plate("P_1", size=self.num_groups, subsample=idx.get("P_1"), dim=-1, device=self.device)
plate_P_0 = pyro.plate("P_0", size=self.num_observations, subsample=idx.get("P_0"), dim=-2, device=self.device)
return (plate_P_1, plate_P_0)
def forward(
self,
data: torch.Tensor | None = None,
idx: dict | None = None,
):
"""
Define the three-level Hierarchical Gaussian Model.
Args:
data: observed data of shape (num_observations, num_groups, dim)
idx: optional mapping from plate name ("P_1", "P_0") to subsample indices.
The PAVI guide calls the model as `model(data, idx)`.
"""
plate_P_1, plate_P_0 = self.create_plates(data, idx)
# Level 1: Global latent variable z_2 of dimension dim
z_2 = pyro.sample(
"z_2",
dist.Normal(
loc=torch.zeros(self.dim, device=self.device),
scale=torch.ones(self.dim, device=self.device),
).to_event(1),
) # shape: (dim,)
# Level 2: Group-level latent variables z_1^i for i = 1, ..., num_groups
with plate_P_1:
# z_1^i depends directly on z_2 (no projection, same dimension)
z_1 = pyro.sample(
"z_1",
dist.Normal(loc=z_2, scale=self.sigma_1).to_event(1),
) # shape: (num_groups, dim)
# Level 3: Observed variables X^{i,j}
with plate_P_0:
# X^{i,j} depends directly on z_1^i (no projection, same dimension)
pyro.sample(
"X",
dist.Normal(loc=z_1, scale=self.sigma_0).to_event(1),
obs=data,
) # shape: (num_observations, num_groups, dim)
Step 2 - Visualize the model and draw a sample¶
In this step, we perform three actions to understand and visualize the Hierarchical Gaussian Model:
Render the model structure: Use
pyro.render_model()to generate a graphical representation of the three-level hierarchical model, showing all distributions and their dependencies.Sample from the generative model: Use
pyro.poutine.trace()to draw a single sample from the model and capture the values of all latent and observed variables. The random seedSEEDis set right before sampling, so the dataset (and everything downstream) is reproducible:- \(z_2 \in \mathbb{R}^{\text{dim}}\): the global latent (shape:
(dim,)) - \(z_1 \in \mathbb{R}^{\text{num\_groups} \times \text{dim}}\): the group-level latents (shape:
(num_groups, dim)) - \(X \in \mathbb{R}^{\text{num\_observations} \times \text{num\_groups} \times \text{dim}}\): the observations (shape:
(num_observations, num_groups, dim))
- \(z_2 \in \mathbb{R}^{\text{dim}}\): the global latent (shape:
Plot the 2D sample: Create a scatter plot to visually inspect the hierarchical structure:
- Red star: the global latent \(z_2\), shared across all groups
- Black crosses: the group-level latents \(z_1^i\), one per group, positioned around \(z_2\)
- Colored scatter points: the observations \(X^{i,j}\), grouped by color, showing within-group variation around each \(z_1^i\)
import matplotlib.pyplot as plt
import seaborn as sns
# Hyperparameters for the 2D example
DIM = 2
NUM_GROUPS = 5
NUM_OBSERVATIONS = 50
SIGMA_1 = 5.0
SIGMA_0 = 1.0
DEVICE = "cpu" # the toy model is tiny, CPU is faster than GPU/MPS here
SEED = 0 # seeds torch, numpy and random through `pyro.set_rng_seed`
# Create the model
model = ModelHGM(
dim=DIM,
num_groups=NUM_GROUPS,
num_observations=NUM_OBSERVATIONS,
sigma_1=SIGMA_1,
sigma_0=SIGMA_0,
device=DEVICE,
)
# Render the model to visualize its structure
pyro.render_model(model, model_args=(), render_distributions=True)
# Sample from the generative model (seeded here, so re-running this cell gives the same dataset)
pyro.set_rng_seed(SEED)
with pyro.poutine.trace() as trace:
model()
z_2 = trace.trace.nodes["z_2"]["value"] # shape: (dim,)
z_1 = trace.trace.nodes["z_1"]["value"] # shape: (num_groups, dim)
X = trace.trace.nodes["X"]["value"] # shape: (num_observations, num_groups, dim)
# Plot the sample
fig, ax = plt.subplots(figsize=(8, 8))
colors = sns.color_palette("husl", NUM_GROUPS)
for i in range(NUM_GROUPS):
ax.scatter(
X[:, i, 0].cpu().numpy(),
X[:, i, 1].cpu().numpy(),
color=colors[i],
alpha=0.4,
s=10,
label=f"Group {i + 1}",
)
ax.scatter(
z_1[:, 0].cpu().numpy(),
z_1[:, 1].cpu().numpy(),
marker="x",
s=100,
c="black",
label="$z_1$ (group means)",
)
ax.scatter(
z_2[0].item(),
z_2[1].item(),
marker="*",
s=250,
c="red",
label="$z_2$ (global mean)",
)
ax.set_xlabel("$x_1$")
ax.set_ylabel("$x_2$")
ax.set_title("2D Hierarchical Gaussian Model")
ax.legend(loc="best")
ax.set_aspect("equal")
plt.tight_layout()
plt.show()
Step 3 - Create the PAVI guide¶
The sample drawn above is now treated as the observed dataset \(X\), and we approximate the posterior \(p(z_2, z_1 \mid X)\) with a PAVIGuide. Each latent site gets its own chain of transforms, applied to a standard Normal base by the NormalizingFlowScheme:
- \(z_2\) (global, outside any plate): a single
affinetransform with learnable location and diagonal scale, i.e. \(q(z_2) = \mathcal{N}(\mu_2, \text{diag}(s_2^2))\). - \(z_1^i\) (inside plate \(P_1\)): a
conditional_affinetransform shared across groups. Its location and scale are produced by a small neural network fed with a learnable encoding \(E_i\) for each group \(i\) (managed byJointEM), so \(q(z_1^i) = \mathcal{N}(\mu_\phi(E_i), \text{diag}(s_\phi(E_i)^2))\). The number of parameters therefore grows with the encoding size, not with the number of groups.
The observed site X is passed as a hidden site so that the guide does not score it.
from pavi.core import JointEM, NormalizingFlowScheme, PAVIGuide
from pavi.distributions import affine, conditional_affine
ENCODING_SIZE = 2
guide = PAVIGuide(
model=model,
transform_modules={
"z_2": [affine(scale_type="diag", scale_init=1.0)],
"z_1": [conditional_affine(hidden_layers=[32, 32], scale_type="diag")],
},
transform_scheme=NormalizingFlowScheme,
encoding_manager=JointEM(encoding_size={"P_1": ENCODING_SIZE}),
hidden_sites=["X"],
device=DEVICE,
data=X, # forwarded to the model to trace its structure
)
guide
PAVIGuide(
(encodings): ModuleDict(
(P_1): PyroEmbedding(5, 2)
)
(z_2): PyroModule(
(0_transform): AffineModule()
)
(z_1): PyroModule(
(0_transform): ConditionalAffineModule(
(transform): ConditionalAffineNN(
(loc_nn): DenseNN(
(layers): ModuleList(
(0): Linear(in_features=2, out_features=32, bias=True)
(1): Linear(in_features=32, out_features=32, bias=True)
(2): Linear(in_features=32, out_features=2, bias=True)
)
(f): LeakyReLU(negative_slope=0.01)
)
(scale_nn): DenseNN(
(layers): ModuleList(
(0): Linear(in_features=2, out_features=32, bias=True)
(1): Linear(in_features=32, out_features=32, bias=True)
(2): Linear(in_features=32, out_features=2, bias=True)
)
(f): LeakyReLU(negative_slope=0.01)
)
)
)
)
)
Step 4 - Train the guide¶
We maximize the ELBO with Adam and gradients that flow through the reparameterized samples. Since the guide is a PyroModule, its parameters (affine parameters, conditional networks and encodings) are accessible through guide.parameters(). The learning rate decays exponentially from \(10^{-2}\) to \(10^{-3}\) to reduce the noise of the final estimates.
from pyro.infer import Trace_ELBO
from tqdm.auto import tqdm
NUM_STEPS = 2000
NUM_PARTICLES = 8
pyro.set_rng_seed(SEED)
elbo = Trace_ELBO(num_particles=NUM_PARTICLES, max_plate_nesting=2)
optimizer = torch.optim.Adam(guide.parameters(), lr=1e-2)
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.1 ** (1 / NUM_STEPS)) # lr: 1e-2 -> 1e-3
losses = []
for _ in tqdm(range(NUM_STEPS)):
optimizer.zero_grad()
loss = elbo.differentiable_loss(model, guide, X)
loss.backward()
optimizer.step()
scheduler.step()
losses.append(loss.item())
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(losses)
ax.set_yscale("log")
ax.set_xlabel("step")
ax.set_ylabel("negative ELBO")
ax.set_title("Training loss")
plt.tight_layout()
plt.show()
100%|██████████| 2000/2000 [00:21<00:00, 92.29it/s]
Step 5 - Compare with the analytical posterior¶
The HGM is linear-Gaussian, so its posterior is known in closed form. It factorizes over the dim coordinates, so the formulas below apply per coordinate. Let \(\bar{X}^i = \frac{1}{N_{\text{obs}}} \sum_j X^{i,j}\) and \(v = \sigma_1^2 + \sigma_0^2 / N_{\text{obs}}\) (marginally, \(\bar{X}^i \mid z_2 \sim \mathcal{N}(z_2, v)\)):
- Global level: \(z_2 \mid X \sim \mathcal{N}(m_2, \lambda_2^{-1})\) with \(\lambda_2 = 1 + N_{\text{groups}} / v\) and \(m_2 = \lambda_2^{-1} \sum_i \bar{X}^i / v\).
- Group level: with \(\lambda_1 = 1/\sigma_1^2 + N_{\text{obs}}/\sigma_0^2\), the marginal posterior is \(z_1^i \mid X \sim \mathcal{N}\left(\lambda_1^{-1}\left(m_2/\sigma_1^2 + N_{\text{obs}} \bar{X}^i / \sigma_0^2\right),\ \lambda_1^{-1} + (\sigma_1^2 \lambda_1)^{-2} \lambda_2^{-1}\right)\).
The guide treats \(z_2\) and \(z_1\) as independent (mean-field across levels), so it cannot represent their posterior correlation. Here that correlation is negligible because \(\sigma_1 \gg \sigma_0 / \sqrt{N_{\text{obs}}}\), so the PAVI marginals should match the exact ones.
# Analytical posterior (identical and independent across the `dim` coordinates)
x_bar = X.mean(0) # (num_groups, dim), group means of the observations
var_x_bar = SIGMA_1**2 + SIGMA_0**2 / NUM_OBSERVATIONS
precision_z_2 = 1 + NUM_GROUPS / var_x_bar
z_2_post_mean = x_bar.sum(0) / var_x_bar / precision_z_2
z_2_post_std = precision_z_2**-0.5
precision_z_1 = 1 / SIGMA_1**2 + NUM_OBSERVATIONS / SIGMA_0**2
z_1_post_mean = (z_2_post_mean / SIGMA_1**2 + NUM_OBSERVATIONS * x_bar / SIGMA_0**2) / precision_z_1
z_1_post_std = (1 / precision_z_1 + (1 / (SIGMA_1**2 * precision_z_1)) ** 2 / precision_z_2) ** 0.5
from matplotlib.lines import Line2D
# Draw posterior samples from the trained guide
NUM_SAMPLES = 1000
pyro.set_rng_seed(SEED)
with torch.no_grad():
guide_samples = [guide(X) for _ in range(NUM_SAMPLES)]
z_2_q = torch.stack([s["z_2"] for s in guide_samples]) # (NUM_SAMPLES, dim)
z_1_q = torch.stack([s["z_1"] for s in guide_samples]) # (NUM_SAMPLES, num_groups, dim)
# Compare the moments of the PAVI posterior with the analytical posterior
print(f"{'variable':<10} {'true value':>22} {'exact mean':>22} {'PAVI mean':>22} {'exact std':>12} {'PAVI std':>22}")
rows = [("z_2", z_2, z_2_post_mean, z_2_post_std, z_2_q)] + [
(f"z_1[{i}]", z_1[i], z_1_post_mean[i], z_1_post_std, z_1_q[:, i]) for i in range(NUM_GROUPS)
]
for name, true, mean, std, q in rows:
print(
f"{name:<10} {str(true.cpu().numpy().round(3)):>22} {str(mean.cpu().numpy().round(3)):>22}"
f" {str(q.mean(0).cpu().numpy().round(3)):>22} {std:>12.3f} {str(q.std(0).cpu().numpy().round(3)):>22}"
)
def plot_posterior(ax, samples, true_value, exact_mean, color):
"""Plot PAVI posterior contours, the PAVI mean, the exact posterior mean and the true value of a 2D latent."""
samples = samples.cpu().numpy()
sns.kdeplot(x=samples[:, 0], y=samples[:, 1], ax=ax, color=color, levels=5, linewidths=1)
pavi_mean = samples.mean(0)
ax.scatter(*true_value.cpu().numpy(), marker="x", s=100, c="black", zorder=3)
ax.scatter(*exact_mean.cpu().numpy(), marker="+", s=200, c="red", linewidths=2, zorder=3)
ax.scatter(*pavi_mean, marker="o", s=60, facecolors="none", edgecolors=color, linewidths=2, zorder=3)
ax.set_xlabel("$x_1$")
ax.set_ylabel("$x_2$")
ax.set_aspect("equal", adjustable="datalim")
def legend_handles(color):
return [
Line2D([], [], color=color, linewidth=1, label="PAVI posterior (contours)"),
Line2D([], [], marker="o", linestyle="none", markerfacecolor="none", markeredgecolor=color, markersize=8, label="PAVI mean"),
Line2D([], [], marker="+", linestyle="none", color="red", markersize=12, markeredgewidth=2, label="exact posterior mean"),
Line2D([], [], marker="x", linestyle="none", color="black", markersize=9, label="true value"),
]
variable true value exact mean PAVI mean exact std PAVI std z_2 [ 1.541 -0.293] [-0.429 -0.099] [-0.397 -0.176] 0.913 [0.919 0.898] z_1[0] [-9.353 2.549] [-9.351 2.401] [-9.332 2.377] 0.141 [0.147 0.149] z_1[1] [-3.882 -7.286] [-3.981 -7.257] [-4.002 -7.26 ] 0.141 [0.143 0.14 ] z_1[2] [3.558 3.897] [3.816 3.892] [3.88 3.91] 0.141 [0.145 0.142] z_1[3] [-2.055 -2.31 ] [-1.953 -2.432] [-1.919 -2.425] 0.141 [0.153 0.141] z_1[4] [-1.442 0.617] [-1.411 0.428] [-1.385 0.428] 0.141 [0.141 0.142]
# Group level: one panel per group, zoomed on the posterior of z_1^i
fig, axes = plt.subplots(1, NUM_GROUPS, figsize=(4 * NUM_GROUPS, 4.5), squeeze=False)
for i, ax in enumerate(axes[0]):
plot_posterior(ax, z_1_q[:, i], z_1[i], z_1_post_mean[i], colors[i])
ax.set_title(f"$z_1^{{{i + 1}}}$ (group {i + 1})")
fig.legend(handles=legend_handles("gray"), loc="lower center", ncol=4, frameon=False)
fig.suptitle("Group level: posterior of $z_1$")
plt.tight_layout(rect=(0, 0.08, 1, 1))
plt.show()
# Global level: posterior of z_2
fig, ax = plt.subplots(figsize=(6, 6))
plot_posterior(ax, z_2_q, z_2, z_2_post_mean, "tab:blue")
ax.set_title("Global level: posterior of $z_2$")
ax.legend(handles=legend_handles("tab:blue"), loc="best")
plt.tight_layout()
plt.show()