betaFeedback

WorksMathematics

NFDiag\texttt{NFDiag}: High-dimensional MCMC Convergence Diagnosis with Normalizing Flows

Abstract

Accurately assessing the convergence of Monte Carlo Markov Chains is crucial for ensuring their validity in Bayesian inference problems. However, convergence assessment in high dimensions is known to be difficult, due to most convergence diagnostics becoming insensitive beyond a few dozen parameters. Conventional convergence statistics analyze marginal distributions which in high dimensions neglects increasing levels of information from the joint and conditional probability distributions. Thus we propose NFDiag\texttt{NFDiag}, which taps into the information of the full multivariate joint posterior with a normalizing flow (NF). Our convergence diagnostic thereby also analyzes information from conditional distributions. In other words, by working in the full multivariate space, it is sensitive with respect to the geometry of the chain in high dimensions. Our diagnostic utilizes that NFs assume independent and identically distributed (iid) training samples, which is a testable assumption that will be violated by a non-converged or strongly correlated chain. Our diagnostic trains NFs on separate parts of a chain, and then assesses whether these correspond to the same multivariate target distribution. We test our diagnostic in up to 250 dimensions, and demonstrate it is universal and unbiased, and detects problematic chain quality also when Gelman-Rubin R^\hat{R} and the multivarite effective sample size do not.

Introduction

Bayesian statistics ((Bayes 1763; Fienberg 2006)) provides a practical framework for solving scientific inference problems. While some Bayesian inference problems can be solved completely analytically, most rely heavily on computational methods ((Gelman et al. 2013)), such as Markov Chain Monte Carlo (MCMC) ((Metropolis et al. 1953; Hastings 1970)) algorithms. Following the initial Metropolis-Hastings algorithm, more variations of MCMC were developed, such as the Gibbs sampler ((Geman & Geman 1984; Gelfand & Smith 1990)), the Hamiltonian Monte Carlo (HMC) sampler ((Duane et al. 1987)), piecewise deterministic samplers ((Bertazzi & Bierkens 2022)), the No U-Turn sampler (NUTS) ((Hoffman & Gelman 2014)) and the affine invariant sampler ((Goodman & Weare 2010)).

As these algorithms allowed for sampling from more complex and increasingly higher dimensional probability distributions, a typical research question became: How can one tell that a chain is of sufficient quality to faithfully represent the target distribution? This is usually abbreviated to the question of whether the chain has converged.

In dimensions beyond a few dozen, this question becomes increasingly hard to answer, and this paper hence proposes a diagnostic for chain quality assessment in high dimensions.

One prerequisite for convergence is that the chain has sufficiently mixed and explored all the subvolumes of the probability distribution. This is implicitly a question about the geometric shape of the chain in high dimensions. This geometry contains valuable information about whether the chain correctly resolves the conditionals of the target distribution.

The most popular convergence diagnostics analyze marginals of the chain only. These include visual inspection of marginal scatter plots, the correlation length of the chain and the effective sample size (ESS) ((Geyer 1992)), Gelman-Rubin’s R^\hat{R} ((Gelman & Rubin 1992)) and Hanson’s diagnostic ((Hanson 2001)).

Restricting the analysis to marginals only loses information. For example, unexplored sub-volumes typically become invisible when projecting down onto a 2-dimensional marginal, and a convoluted trace of the chain in the full volume can look like a well-mixed chain in a 2-dimensional projection. In the following, we therefore train normalizing flows (NFs) to use the information in the conditional distributions on top of that in the marginals.

We utilize NFs to construct the posterior of samples from an MCMC chain. NFs assume the samples used to train its neural networks to be independent and identically distributed (iid), and a chain that is yet to converge contradicts this assumption. Thus a NF model built with samples falsely assuming iid will fail to accurately represent another chain from the same target distribution. Our code NFDiag harnesses this fact to render the lack of convergence in MCMC chains visible. It computes a new convergence statistic in high dimensions we have called NFD, given by Eq. (8), which is the main result of this paper.

We structure this work as follows. Further details about NF and the theoretical formulation that makes NFDiag possible are given in § 2 and 3. We provide a brief user guide to NFDiag in § 4. § 5 demonstrates our method is universal and unbiased in up to 125 dimensions, and highlights its advantages in comparison with other common statistics. In § 5.3, we test it on a presently relevant cosmological inference problem in 250 dimensions. In § 6, we conclude.

Methodology

NFDiag relies on normalizing flows (NFs) to model the joint probability distribution of a (or part of a) chain of samples acquired from a Markov Chain Monte Carlo (MCMC) sampler. We provide a brief introduction to NFs in § 2.1. Crucially, we outline the capabilities of NF models and how they relate to NFDiag in 2.2.

Normalizing Flows

NFs aim to represent an intractable probability distribution as a series of variable transformations of a known probability distribution. We denote the former as PX(x)P_{\mathcal{X}}(\mathbf{x}) for x∈X\mathbf{x} \in\mathcal{X}, and the latter with PU(u)P_{\mathcal{U}}(\mathbf{u}) for u∈U\mathbf{u} \in\mathcal{U}. Then, let f1≤i≤n∈Ff_{1 \leq i \leq n} \in\mathcal{F} be nn functions in the family of diffeomorphisms F\mathcal{F}. NFs aim to establish a probability-preserving relation of the form

x=fn∘fn−1∘…∘f1(u),(1)\mathbf{x} = f_n \circ f_{n-1} \circ\ldots\circ f_1(\mathbf{u}), \tag*{(1)}

between the domains of PX(x)P_{\mathcal{X}}(\mathbf{x}) and PU(u)P_{\mathcal{U}}(\mathbf{u}). Preservation of probability density requires that

PX(x)=∏i=1n∣det⁡dfi(zi−1)dzi∣PU(u),(2)P_{\mathcal{X}}(\mathbf{x}) = \prod_{i=1}^{n} \left\lvert\det\frac{\mathrm{d}f_i(\mathbf{z}_{i-1})}{\mathrm{d}\mathbf{z}_i} \right\rvert P_{\mathcal{U}}(\mathbf{u}), \tag*{(2)}

where zi=fi(zi−1)\mathbf{z}_i = f_i(\mathbf{z}_{i-1}) are representations of the intermediate variables of the transformations (with z0=u\mathbf{z}_0 = \mathbf{u} and zn+1=x\mathbf{z}_{n+1} = \mathbf{x}). The change of variables formula given by Eq. (2) allows the probability of any x\mathbf{x} to be uniquely calculated without PXP_{\mathcal{X}}, relying only on the Jacobian matrix and the probability PU(u)P_{\mathcal{U}}(\mathbf{u}). The complete mathematical derivation of NF is presented in Papamakarios et al. (2019).

While n≫1n \gg1 is required for above to hold, in practice, it might be impossible to find fif_i with a finite or small nn such that Eq. (2) remains computable in a reasonable amount of time. Thus realistically, Eqs. (1) and (2) are only approximately satisfied, with fif_i specifically selected from families of functions with high expressive flexibility. Let θ\boldsymbol{\theta} denote the hyperparameters of such a set of fif_i, and FθF_{\boldsymbol{\theta}} the resulting approximate representation of PXP_{\mathcal{X}}. θ\boldsymbol{\theta} are then optimized via minimizing a distance metric between FθF_{\boldsymbol{\theta}} and PXP_{\mathcal{X}} to ensure the approximation is as close to equality as possible.

Conventionally for NF models, the hyperparameters θ\boldsymbol{\theta} are represented as neural networks (NN), and the distance metric, or loss function, is the forward Kullback-Leibler (KL) divergence (Kullback & Leibler 1951), given by

DKL(PX∥Fθ)=∫PX(x)log⁡(PX(x)Fθ(x)) dx=−EPX(x)[log⁡Fθ]+constant.(3)\begin{aligned} D_{\mathrm{KL}}(P_{\mathcal{X}} \mathbin{\|} F_{\boldsymbol{\theta}}) = \int P_{\mathcal{X}}(\mathbf{x}) \log\left(\frac{P_{\mathcal{X}}(\mathbf{x})}{F_{\boldsymbol{\theta}}(\mathbf{x})}\right) \,\mathrm{d}\mathbf{x} \\ &= -\mathbb{E}_{P_{\mathcal{X}}(\mathbf{x})}[\log F_{\boldsymbol{\theta}}] + \text{constant}. \tag*{(3)} \end{aligned}

Here the constant term is the expectation under PXP_{\mathcal{X}} of log⁡PX\log P_{\mathcal{X}}; since it does not vary as the NF model is trained, we drop it when minimizing DKLD_{\mathrm{KL}}.

Sensitivity to Sample Quality

In practice, the integral of Eq. (3) has to be calculated with a sample-based Monte Carlo estimator. The expectation value in the KL divergence of Eq. (3) is approximated by the Monte Carlo integral

DKL(PX∥Fθ)=−1N∑n=1Nlog⁡Fθ(xn)=L(θ),(4)\begin{aligned} D_{\mathrm{KL}}(P_{\mathcal{X}} \mathbin{\|} F_{\boldsymbol{\theta}}) = -\frac{1}{N}\sum_{n=1}^{N}\log F_{\boldsymbol{\theta}}(\mathbf{x}_n) \\ &= \mathcal{L}(\boldsymbol{\theta}), \tag*{(4)} \end{aligned}

which assumes that the set of samples {xn}n=1N\{\mathbf{x}_n\}_{n=1}^{N} are independently and identically drawn (iid) from the target distribution PXP_{\mathcal{X}}.

Crucially, if the samples are not iid, L(θ)\mathcal{L}(\boldsymbol{\theta}) will no longer be an unbiased approximator of DKLD_{\mathrm{KL}}. Then minimizing L(θ)\mathcal{L}(\boldsymbol{\theta}) will produce an NF model FθF_{\boldsymbol{\theta}} that is a biased approximation of PXP_{\mathcal{X}} (Kirchler et al. 2022), but a faithful fit to the imperfect MCMC samples, pretending they were iid. The resulting NF will hence include information on the imperfections of the MCMC chain.

Consequently, if a problematic MCMC chain is split into several subsections, and NF models are trained on each of these subsections, then the resulting NFs will all differ from each other. Each of these NFs will then assign a low probability to samples of other sub-sections of the chain.

In brief, for a bad chain, each NF will be a bad statistical model for samples from other sections of the chain, whereas a good chain will result in NFs that agree. The new MCMC convergence diagnostic we will detail upon in the following Sec. relies on this discrepancy. In practice, the direct comparison of an NF model to unseen samples is dependent on the exact PXP_{\mathcal{X}} and hyperparameters of the NF architecture. To drop this dependency, a normalization via training of several flows is necessary. These details will also be discussed in the following section.

NFDiag: MCMC Convergence using Normalizing Flows

An MCMC sampler builds up a chain of length LL of samples of the parameters Θ1\boldsymbol{\Theta}^{1} generated from a posterior function PP conditioned on the data d\mathbf{d} given by P(Θ∣d)≡PP(\boldsymbol{\Theta}|\mathbf{d}) \equiv P. Often one runs several such chains, and we denote the iith such MCMC chain as Si={Θi,k}k=1L\mathcal{S}_i = \{\boldsymbol{\Theta}_{i,k}\}_{k=1}^{L}, where i∈[1,m]i \in[1,m] for mm chains. Each of these chains will separately satisfy that its number density ni(Θ)n_i(\boldsymbol{\Theta}) of samples will be proportional to a probability density PiP_i

ni(Θ)∝Pi(Θ).(5)n_i(\boldsymbol{\Theta}) \propto P_i(\boldsymbol{\Theta}). \tag*{(5)}

Chain Si\mathcal{S}_i is considered converged when the density of samples PiP_i is proportional to the target density PP over the entire domain of Θ\boldsymbol{\Theta}. If the chains are not converged, then these individual densities PiP_i will differ from each other, Pi(Θ)≠Pj(Θ), ∀i≠jP_i(\boldsymbol{\Theta}) \ne P_j(\boldsymbol{\Theta}), \ \forall i \ne j, and this implies that they cannot be trusted to represent the target density P(Θ∣d)P(\boldsymbol{\Theta}|\mathbf{d}).

Let S1\mathcal{S}_1 and S2\mathcal{S}_2 be two chains. To quantify whether they represent compatible distributions, we train an NF model FθF_{\boldsymbol{\theta}} on S1\mathcal{S}_1 and compare it to S2\mathcal{S}_2 such that the second chain serves as validation chain.

To do so, we evaluate the NF-based probabilities FSi={Fθ(Θi,k)}k=1LF_{\mathcal{S}_i} = \{F_{\boldsymbol{\theta}}(\boldsymbol{\Theta}_{i,k})\}_{k=1}^{L} for i∈[1,2]i \in[1,2] for the samples Θi,k\boldsymbol{\Theta}_{i,k} in the two chains, and compute a distance d(FS1,FS2)d(F_{\mathcal{S}_1}, F_{\mathcal{S}_2}) between them. We detail upon this distance metric in § 3.1. This distance measures whether an NF model trained on one chain assigns a large probability to the samples of another chain, which will be the case if the chains are good, and otherwise not.

If both S1S_1 and S2S_2 are converged to target, then FSi∝PF_{S_i} \propto P and

d(FS1,FS2)=T(L),(6)d(F_{S_1},F_{S_2}) = T(L), \tag*{(6)}

for some threshold T(L)T(L) that depends on the chain length LL and act as lim⁡L→∞T(L)=0\lim_{L\to\infty} T(L) = 0 due to Eq. (5).

If either are not converged, than FS1∝̸FS2F_{S_1} \not\propto F_{S_2}, and d(FS1,FS2)>T(L)d(F_{S_1},F_{S_2}) > T(L) due to the biases in FθF_\theta as outlined in § 2.2. Thus, computing the probability evaluations FSiF_{S_i} via the NF model, followed by the distance dd between them allows us to quantify the compatibility and convergence to target of the chains S1S_1 and S2S_2.

Distance Metric for Convergence Assessment

For the distance metric dd, we adopt the Bhattacharyya distance Bhattacharyya (1943) as implemented in OpenCV Bradski (2000). The advantage of this distance is that it is bounded to the interval [0,1][0,1], where the minimum is achieved for identical distributions. For two histograms H1H_1 and H2H_2 with NN bins, OpenCV implements this distance by

dB(H1,H2)=1−1Hˉ1Hˉ2N∑IH1(I)×H2(I),(7)d_B(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H}_1\bar{H}_2}N}\sum_I \sqrt{H_1(I)\times H_2(I)}}, \tag*{(7)}

where the index II runs over the bins of the histograms and Hˉ1,Hˉ2\bar{H}_1,\bar{H}_2 are the mean counts. We illustrate dBd_B below in Figure 1, where we plot histograms of sample densities drawn from two Gamma distributions f(x,a)f(x,a) for a=[2,4]a=[2,4].

Sample density histograms for two Gamma distributions

Figure 1. Sample density histograms H1H_1 and H2H_2 for two Gamma distributions f(x,a)f(x,a) for a=[2,4]a=[2,4]. We outline the overlap region of the two histograms with dark purple. As the volume of the overlap region increases, dBd_B decreases.

As such, we compute the distance d(FS1,FS2)=dB(HS1,HS2)d(F_{S_1},F_{S_2}) = d_B(H_{S_1},H_{S_2}), where HSiH_{S_i} are the binned probability evaluations FSiF_{S_i}. We discuss how NFDiag automatically optimizes binning in Appendix § 9.

Both binning and NNs are dependent on some hyperparameters, which could affect dBd_B. One cannot ignore this dependency, as similar values of dBd_B could then indicate different states of convergence across problems with different target distributions PXP_X.

To remove this dependency, we normalize dBd_B in the following manner to reduce its sensitivity to hyperparameters of binning, the NF models and the shape of the target distribution.

We first join the two MCMC chains S1S_1 and S2S_2 used in training and validation respectively. We shuffle the positions of the samples in this combined chain such to destroy the correlations between successive samples. Then, we re-separate the shuffled combined chain into two random chains R1R_1 and R2R_2 such that the length of RiR_i matches length of SiS_i.

Then, we train a second NF model we name FpairF_{\rm pair} whose architecture and hyperparameters are identical to those of FθF_\theta. We compute a second distance dB,pair=dB(HR1,HR2)d_{B,\rm pair}=d_B(H_{R_1},H_{R_2}) used in normalization. Then, the normalized diagnostic we call NFD is given by

NFD=1−dB1−dB,pair.(8)\mathrm{NFD} = \frac{1-d_B}{1-d_{B,\mathrm{pair}}}. \tag*{(8)}

This way, we succeed in dropping any variation in dBd_B due to differences in training of the NF model, binning of the histograms, and original target distribution. The resulting statistic NFD is then such that NFD ≈1\approx1 corresponds to total convergence and NFD ≈0\approx0 to total lack of overlap in the number densities of the samples in the two chains.

A minor side effect of the division in Eq. (8) is that NFD ≳1\gtrsim1 is possible when samples are iid due to variances in model fitting or dBd_B computation. This means our convergence diagnostic can, due to noise, slightly exceed the value of unity in case of a perfect chain.

We provide a short user guide for this statistic in the following section, and demonstrate its performance in § 5.

User Guide for NFDiag

NFDiag is our NF-based code that uses MCMC chains as input and computes a convergence diagnostic NFD for them. In this section, we detail on the code of NFDiag, and provide a guide of its features for users.

For the NFs, we use neural spline flows (Durkan et al. (2019)): rational quadratic splines with knot points and derivatives predicted by NN. Normflows (Stimper et al. (2023)) provides both the masked coupling and the autoregressive neural spline flows2. We acknowledge that the latter would be faster to train and evaluate for probabilities, but we have used the former for faster sampling for diagnostics. The user can swap NFDiag between the variants, and we have noticed no difference in results obtained from doing so.

A central aspect of NN-based research is the potential of overfitting (Geman et al. (1992)). To combat this, we utilize dropout (Srivastava et al. (2014)), L2 regularization (Krogh & Hertz (1991)) and early stopping. A common approach is to terminate training as soon as the mean validation loss increases. However, there is evidence that this is an oversimplification of real NN training (Prechelt (2000)).

We implement a early stopping method that assigns a penalty for increases in the loss function and dBd_B until a budget for the penalty is exceeded. To accurately compute3 the training losses, after every epoch and freezing the NN weights, the loss in Eq. (4) is reevaluated on the entire training chain in addition to the validation chain. Then, once the cumulative penalties exceed the budget, the training is stopped. The penalties and the budget are hyperparameters that control the trade-off between the generalization of the model and the training time and can be tuned by the user to adapt to their use case.

To run NFDiag for assessing the quality of their MCMC chains, the user needs to provide

  • files for chains S1S_1 and S2S_2, or alternatively only S1S_1 which the code then splits into S1S_1 and S2S_2

  • number of epochs to train NF models for

  • snapshot frequency, which defines the epochs where NFD is computed and plots are produced.

NFDiag then will automatically:

  • Assign S1S_1 to training and S2S_2 to validation. If only S1S_1 is provided, assign the first 70% to training, and rest to validation.

  • Train an NF model FθF_\theta on S1S_1

  • At the snapshot epochs, save a copy of the model and the probability evaluations FS1F_{S_1} and FS2F_{S_2}.

  • Once the NF model converges or the maximum number of epochs is reached, repeat the above 3 steps, but for the pair model FpairF_{\mathrm{pair}} which is trained instead on R1R_1 as defined in § 3.1.

  • Histogram the probability evaluations FSiF_{S_i} and Fpair,RiF_{\mathrm{pair},R_i} for i∈[1,2]i \in[1,2] and compute NFD for every snapshot.

All hyperparameters of the models and NN training can also be specified by the user. We provide sensible values for these in § 5 alongside our demonstrations of NFDiag.

Demonstrations of NFDiag

In this section, we demonstrate NFDiag across different experiments. In § 5.1, we establish that NFD is a universal and unbiased indicator of multivariate convergence in up to 125 dimensions. § 5.2 is dedicated to applying NFDiag to chains from various MC samplers.

Due to runtimes, it is difficult to systematically demonstrate reliable performance of NFDiag in higher dimensions than 125, even though we found good performance in all higher dimensional tests we performed. We hence demonstrate in § 5.3, an application of NFDiag to chains of the weak lensing power spectrum in 250 dimensions. This demonstrates the science-readiness of NFDiag as the weak lensing power spectrum is a common approach to inferring parameters of the current cosmological models using large scale matter distribution in the universe.

The hyperparameters common to all NF models are displayed in Table 1. We have independently verified that choosing different values will not significantly alter the results we present here and solely affect the point at which the NF models converge.

HyperparameterValueHyperparameterValue
Flow layers3Batch size5k
NN layers3Spline knots20
Neurons/layer512Dropout0.45
Learning rate10−310^{-3}Weight decay0.005

Table 1. Hyperparameters shared between all NF models and training regimens for the experiments in § 5.

All experiments were performed on an Asus Zephyrus S GX701GWR with Intel Core i7-9750H CPU, 16.0 GB of RAM and an NVIDIA GeForce RTX 2070 GPU with 8GB of VRAM using Python 3.13.5 and PyTorch 2.7.1 with CUDA 11.8. They take around 2 to 20 minutes per repetition depending on the dimensionality.

Universality of NFD in the IID Limit

The most popular subclass of MCMC algorithms are so-called ‘universal’ samplers for which it can be shown that they correctly sample from a very wide class of target distributions. It is hence natural to ask whether NFD is also universally applicable to different distributions, or whether it will fail e.g. for multi-modal distributions.

For all distributions we tested, we found NFDiag to be of generic and stable performance. Moreover, as any unimodal and even multimodal multivariate probability distributions can be approximated as a sum of multivariate Gaussian distributions, one can expect universal stable performance of our diagnostic for any probability distribution if the NFD performs well for Gaussian Mixtures (GMs). To demonstrate that our diagnostic even handles multimodal distributions well, we here include into our demonstrations GM distributions in ndims=[5,25,75,125]n_{\mathrm{dims}} = [5, 25, 75, 125] dimensions. For each, we create multimodal distributions consisting of [5,20,100][5, 20, 100] Gaussian components with random mean vectors, covariance matrices and weights, and acquire L=100 000L = 100\,000 iid samples as chains.

To establish NFD is unbiased, in each dimension, we generate iid chains from a multivariate Student’s tt, and a matrix-variate Wishart distribution with L=[1 000,10 000,100 000]L = [1\,000, 10\,000, 100\,000]. Since for a set of iid samples

lim⁡L→∞NFD=1,(9)\lim_{L \to\infty} \mathrm{NFD} = 1, \tag*{(9)}

one would expect the NFD to asymptotically approach unity with increasing LL if the test is truly unbiased. The results are given in Figure 2, which demonstrates the unbiasedness of our diagnostic across all test cases. Note that for the shorter chains, we reduce the batch size from the value in Table 1 to keep the number of batches constant.

NFD values for iid samples in increasing dimensions and several distributions

Figure 2. Evaluating NFD for iid samples in increasing dimensions, and for several distributions. The error bars are standard deviations obtained from 5 repetitions. The multivariate Student’s t and matrix-variate Wishart distributions are indicated with triangles and circles respectively. With increasing LL, the NFD approaches 1, indicating that it is unbiased. The Gaussian Mixture (GM) chains indicated with crosses are all of L=100 000L = 100\,000. Since any probability distribution can be approximated through a GM, we conclude that the NFD is universally applicable to any target distribution as we see here that it performs reliably even for these multimodal distributions.

Comparisons with Other Convergence Statistics

In this section, we apply NFDiag to chains of samples acquired using various auto-correlated MC samplers and compare NFD to other statistics commonly used in assessment of convergence of MCMC chains.

First is the univariate R^\hat{R} ((Gelman & Rubin 1992)) computed on the marginals of the multivariate chains, which aims to evaluate the stationarity of a chain via comparing the within-chain and between-chain variances. We adopt the split-R^\hat{R} from Vehtari et al. (2021), defined as

R^=L−1L+1LBW(10)\hat{R} = \sqrt{\frac{L - 1}{L} + \frac{1}{L}\frac{B}{W}} \tag*{(10)}

where BB and WW are the between- and within-chain variances of a chain of length LL. Vehtari et al. (2021) recommend R^<1.01\hat{R} < 1.01 to indicate marginal convergence. Rather than requiring each marginal to fall below this threshold, we consider our multivariate chains ‘converged wrt. R^\hat{R}’ when the mean of the R^\hat{R}s is less than 1.01.

We also compare against multivariate effective sample size (mESS) proposed by Vats & Knudson (2018), which extends the univariate formulation. Let C^\hat{C} be the sample covariance matrix of a dd-dimensional chain of length LL, and T^L\hat{T}_L be the Monte Carlo error estimate for this chain. Then, the mESS is given by

mESS=L⋅(det⁡C^det⁡T^L)1/d.(11)\mathrm{mESS} = L \cdot\left(\frac{\det\hat{C}}{\det\hat{T}_L}\right)^{1/d}. \tag*{(11)}

Crucially, we use the Monte Carlo error estimator in Banerjee & Vats (2024) for greater accuracy in higher dimensions, which is a hybrid of initial sequence and batch-means estimators. Still, we notice the estimation for the correlation matrix of the mean to be dominated by noise regardless of choice of batch size. This leads to overestimates of mESS up to an order of magnitude in highly correlated chains in high number of dimensions. So, we also compute mESS using the true correlation matrix as the lowest bound. The recommendation of Vehtari et al. (2021) is to aim for at least ESS >400> 400 over an ensemble of chains. In this work, we consider a stricter mESS >1 000> 1\,000 to indicate a chain is ‘converged wrt. mESS’.

We sample chains of a multivariate Gaussian in ndims=[5,25,75,125]n_{\mathrm{dims}} = [5, 25, 75, 125] dimensions, of a fixed length L=100 000L = 100\,000 from three samplers to compute the above statistics and NFD on:

  • Metropolis-Hastings (MH) sampler with a multivariate Gaussian proposal distribution, available through emcee (Foreman-Mackey et al. 2013; Goodman & Weare 2010). Following Roberts et al. (1997), we set the variances of the proposal distribution to l2/dl^2/d for l=[0.1,0.2,0.6,1.2,2.38]l = [0.1, 0.2, 0.6, 1.2, 2.38] where the last value provides the lowest theoretical auto-correlation in a given number of dimensions. The preceding smaller values scale the proposed step sizes down, resulting in greater auto-correlation between the samples.

  • Metropolis-adjusted Langevin algorithm (MALA) sampler (Besag (1994)) in PINTS (Clerx et al. 2019). MALA proposes next states using the local gradient information, but the proposed jump can be scaled with an ϵ\epsilon hyperparameter. We run MALA with ϵ=[0.2,0.3,0.4,0.7]\epsilon= [0.2, 0.3, 0.4, 0.7] to get chains with various auto-correlation lengths akin to the MHMC.

  • Our in-house Hamiltonian Monte Carlo (HMC) sampler (Sellentin et al. 2023; Loureiro et al. 2023) with automated hyperparameter tuning conditioned on a target acceptance rate α\alpha, for α=[0.3,0.5,0.7,0.9]\alpha= [0.3, 0.5, 0.7, 0.9]. The higher target acceptance rates correspond to smaller proposed jump trajectories and vice versa.

Figure 3 shows the comparison between NFD, R^\hat{R} and mESS. Since the R^\hat{R} and mESS adhere to the same general trend, we base our discussion mainly on the latter. Overall, for all ndimsn_{\mathrm{dims}} we have tested, the NFD of a “chain increases with mESS. This indicates that the statistics share a common sensitivity to quality of the chains, and serves to increase confidence in the former’s ability to assess convergence accurately. This can naturally also be extended to R^\hat{R} comparisons.

NFD of chains from different samplers

Figure 3. NFD of chains from different samplers, vs. mean R^\hat{R} and mESS. The points indicate the mESS with the true correlation matrix, while the right-pointing error bars are the MCSE estimator with a batch size of L1/3=47L^{1/3}=47. The dashed lines are provided to navigate the plot by connecting points of the same dimension. The vertical blue region corresponds to chains of allegedly identical convergence quality as assessed by the mESS and R^\hat{R}. Going downwards within these blue regions, one sees that these statistics become insensitive in higher dimensions, whereas NFD continues to resolve difference in convergence quality. As such, we see that mESS and R^\hat{R} incorrectly indicated convergence high dimensions. a select 125-d chains mentioned in addition to iid samples for comparison. From top to bottom: 100 000 iid samples from this distribution, followed by the MALA ϵ=[0.7,0.2]\epsilon=[0.7,0.2], and lastly the MH chain with l=2.38l=2.38. All of these chains are considered converged wrt. mESS and R^\hat{R}, even though the human eye is able to see differences in chain quality: the bottom two chains clearly show heavier and spherically asymmetric tails, which would further be exacerbated when considering the full multivariate geometry of the chain. While this is completely missed by the mESS and R^\hat{R}, NFD accurately flags the problem. This visual impression aligns with the finding that with respect to NFD, only the ϵ=0.7\epsilon=0.7 MALA chain is converged, while the others fall far away from the ideal NFD ≈1\approx1.

The advantage of NFD comes from how it scales across ndimsn_{\mathrm{dims}} in comparison to mESS or R^\hat{R}. Generally, for a fixed value of mESS, the NFD decreases with ndimsn_{\mathrm{dims}}, indicating that the higher dimensional chains are much further from iid (and thus convergence to target) than their lower dimensional counterparts. In turn, a dimension agnostic threshold such as R^<1.01\hat{R} < 1.01 or mESS >1 000> 1\,000 taken as a strong indicator of a well converged chain in a small number of dimensions might not extrapolate to the same degree of convergence in higher.

For example, all of the chains in the region around mESS ≈103\approx10^3 and μlog⁡10(R^−1)≈−2.65\mu_{\log_{10}(\hat{R}-1)} \approx-2.65 highlighted with blue in Figure 3 are considered converged wrt. both mESS and R^\hat{R}. While the assessment wrt. NFD is in agreement for ndims=[5,25]n_{\mathrm{dims}} = [5, 25], note that as the dimensionality of a distribution increases, the conditional information lost by marginalization grows monotonically. While mESS and R^\hat{R} increasingly fail to capture this information, NFD is built to be highly sensitive to it: hence at ndims=[75,125]n_{\mathrm{dims}} = [75, 125], the NFDs are significantly lower when compared to the former ndimsn_{\mathrm{dims}}. In other words, where other diagnostics return over-confident convergence assessments in high dimensions, which simply originate from lost sensitivity, NFD continues to display dynamic behavior in large dimensions, and succeeds in assessing quality of convergence over a larger range of dimensions.

To underline visually that these significantly lower NFDs indeed pick up information that the other diagnostics were insensitive to, we plot in Figure 4 marginals of The decrease in NFD in the transition from the best-performing MALA chains to the worst-performing HMC ones is explained by how NFD assesses convergence: similarity to iid samples from that same distribution. If the HMC sampler accepts a new position as the next sample, the long trajectory lengths afforded by the multistep leapfrog integration ensures low correlation with the previous position. In comparison with algorithms that cannot execute such long jumps, chains acquired from the HMC thus have significantly higher mESS even if they accept new positions at a similar rate. However, at α=[0.3,0.5]\alpha=[0.3,0.5], even an HMC chain will be comprised of a majority of duplicate states. As it is almost impossible for iid samples generated from a (non Dirac-delta) probability distribution to be superimposed, the NFDs of these chains are instead comparable to others with lower mESS.

Marginal plots of iid samples, MALA chains, and an MH chain

Figure 4. Marginal plot of, in order, iid samples, MALA chains with ϵ=[0.7,0.2]\epsilon= [0.7, 0.2] and MH chain with l=2.38l = 2.38, together with their mESS, R^\hat{R} and NFD. The points are colored from orange to black in the sampling order of the chain. All chains are considered converged by mESS and R^\hat{R}, but visually inspecting the marginals reveals convergence problems in the latter two, which would be exacerbated in the full multivariate geometry. NFD is very sensitive to this, and accurately flags the chains as not converged.

Taking all of the iid benchmarks and the tests on various chains from the samplers described in this section, we propose a quality cut of NFD ≥0.9\geq0.9 to consider an MCMC chain adequately converged wrt. NFD. Thus in practice, any value significantly smaller than this should be taken as strong indicator for a lack of multivariate convergence.

250-dimensional Cosmology Example

The primary driver for the development of NFDiag is to provide a statistic that is sensitive and accurate in convergence assessment in high dimensional and topologically complex problems encountered in frontier scientific inference problems. In this section, we demonstrate how NFD can be utilized to ensure the quality of chains in weak lensing power spectrum inference.

We replicate the analysis in Loureiro et al. (2023), albeit in a smaller scale: we limit ourselves to 1 tomographic bin, and generate an Nside=64N_{\mathrm{side}}=64 all-sky shear map with an ℓ\ell-range of [4,128][4,128]. The resulting joint posterior of spherical harmonic coefficients aℓma_{\ell m} and power spectra CℓC_\ell is in 33 625 dimensions. However, in the weak lensing regime, shear is symmetric and curl-free (Stebbins (1996); Bartelmann & Schneider (2001)): therefore the majority cosmological signal is embedded in the 250-dimensional combined power spectrum of CEE,ℓC_{\mathrm{EE},\ell} and CEB,ℓC_{\mathrm{EB},\ell} which we call Csignal,ℓC_{\mathrm{signal},\ell}. While our in-house HMC samples from the joint posterior in 33 625 dimensions, we are primarily interested in the quality of the 250-dimensional Csignal,ℓC_{\mathrm{signal},\ell} samples for the scientific analysis.

This example showcases another unique strength of NFDiag. The probability values of samples generated by the HMC are for the joint posterior of aℓma_{\ell m} and CℓC_\ell, and there is no known analytic integral to marginalize out the contribution of the former to obtain probability values for just the Csignal,ℓC_{\mathrm{signal},\ell}, which could be used to further inform convergence decisions.

NFDiag builds precisely that distribution and can be used to assess convergence of not only full chains, but also multi-dimensional marginals of chains. This is vital in scientific inference precisely: it is common to infer nuisance parameters required by the complex Bayesian hierarchical models alongside parameters of scientific interest in scenarios where the marginal posterior distribution might not be analytically available or highly costly to evaluate numerically.

The chain of length L=100 000L = 100\,000 we sample from this posterior is converged wrt. all of the following widely adopted statistics:

  • bulk ESS (Vehtari et al. 2021) btw. 1000-10000 per ℓ\ell,

  • R^\hat{R} (Gelman & Rubin 1992) less than 1.01 across all ℓ\ell,

  • fraction of missing information (Betancourt 2016) FMI = 0.988,

  • Hanson’s diagnostic (Hanson 2001) btw. [0.95, 1.05] for all ℓ\ell.

We provide plots for all in Appendix § 10.

The NFD ≈0.7\approx0.7 is of this chain is significantly less than NFD ≳0.9\gtrsim0.9 established in § 5.2. Figure 5 plots the histograms of training loss Lt\mathcal{L}_t and validation loss Lv\mathcal{L}_v at model convergence and is automatically generated by NFDiag. The top panel corresponds to the aforementioned chain and displays the NFD, dBd_B and dB,paird_{B,\mathrm{pair}}. The separation between the two histograms directly corresponds to the geometric separation between the halves of the chain. In an iid sample or a well converged chain, one would expect near-perfect overlap of these histograms.

Histograms of training and validation loss

Figure 5. Histograms of the training loss Lt\mathcal{L}_t and validation loss Lv\mathcal{L}_v at Epoch 4 for the NF model trained on (Top) 100 000 Csignal,ℓ\mathrm{C}_{\mathrm{signal},\ell} samples and (Bottom) for 100 000 thinned samples of Csignal,ℓ\mathrm{C}_{\mathrm{signal},\ell} from a longer chain of length 1M from our HMC sampler.

We resume sampling until we acquire a total of 1M samples, and thin the chain to 100 000 samples to have an equivalent analysis (NFDiag results with the unthinned 1M chain are in Appendix C). As expected, this extended and thinned chain has NFD>0.97NFD > 0.97: similar to the multivariate Gaussian in § 5.2. The bottom panel of Figure 5 displays LtL_t and LvL_v histograms for this chain, and the overlap of the two histograms has improved considerably when compared to the former chain.

The scientific inference problem in this Sec. presents a high dimensional MCMC chain that, by various convergence tests, is sufficiently converged. Our convergence assessment with NFDiag utilizing the entirety of the geometric information available in the chain however indicates that the chain is yet to adequately converge. We posit such a wholistic analysis is crucial. Basing a scientific conclusion on such an MCMC chain would yield biased results, as there is no guarantee the sampler has explored the full posterior volume. Resuming the sampler for a significantly longer time generates more effective samples, and improves NFDNFD, increasing the confidence in the convergence of the chain.

Conclusions

Accurately assessing the convergence of MCMC chains is central to avoiding biases in Bayesian inference. Only inspecting marginal distributions of samples can lead to overconfident assessment of convergence, as all information in the joint distribution is ignored. This is particularly problematic in high dimensions.

Our NFs based algorithm NFDiag determines the convergence of high dimensional chains by modeling the posterior of samples from the chain itself. This NF model is then used to evaluate the consistency of the rest of the chain via measuring the degree with which it fails to satisfy the assumption that the samples are iid distributed.

We demonstrate that the NFD is a generic and unbiased metric for summarizing the degree of convergence across all dimensions. In § 5.2, we test the NFD on chains obtained from multiple samplers in up to 125 dimensions.

Finally, we demonstrate NFDiag in 250 dimensions in a relevant Bayesian scientific inference problem, that of cosmological parameter inference from the weak lensing shear field, in § 5.3. We show how NFDiag can spot chains that are not yet fully converged even when the conventional convergence statistics would indicate the contrary.

Acknowledgements

We would like to thank Alan F. Heavens, Andrew H. Jaffe, Lorne Whiteway, Arthur Loureiro and Javier Silva Lafaurie for their help with the weak lensing inference problem in this work and their insightful discussions and comments.

Appendices

dB and Automated Binning

The major variable that influences the distance dBd_B is the number of histogram bins NN. Choosing NN too small would effectively smooth out over the differences in the histograms of comparison, while picking NN too large would cause dBd_B to be dominated by noise.

NFDiag therefore computes the optimal number of bins using the Freedman-Diaconis Rule (Freedman & Diaconis 1981) in cases where L≫1L \gg1, and with the method in Birgé, Lucien & Rozenholc, Yves [8] when the number of samples is small. Alternatively, the user is able to specify their own desired NN to linearly histogram the log probability evaluations.

In cases where strong outliers are present, if the histogram bins are prescribed between the minimal and maximal log probability values, it is highly probable that many of the bins will be under-full or simply empty due to the unrepresentative binning range. This will translate to the effective number of bins in the distance calculation to decrease and bias dBd_B to reporting more similar distributions.

To counteract this technicality, NFDiag removes the bottom and top 0.5% quantiles prior to histogramming. Additionally, NFDiag can be asked to remove under-full bins from the tails post histogram computation, where under-full is defined as a user prescribed fraction of the highest density bin. While this additionally can help cut outlier behavior such as inadvertently included burn-in samples or spurious walkers, we caution users that removing such bins will result in NFDiag signalling improved convergence, as the user removed a sample pathology by hand. We hence recommend users only rely on this when the source of the under-full bins can be identified with confidence.

Conventional Convergence Diagnostics

In this section we provide additional plots for the convergence statistics that were quoted for the scientific inference example in § 5.3. The effective sample size (ESS) ((Geyer 1992; Vehtari et al. 2021)) and Gelman-Rubin R^\hat{R} ((Gelman & Rubin 1992)) are given in Figure 6, and the Hanson’s diagnostic ((Hanson 2001)) and FMI ((Betancourt 2016)) are given in Figure 7.

Effective sample size and R-hat for the 100 000 sample chain

Figure 6. Effective sample size and R^\hat{R} for the 100 000 sample chain.

Hanson's diagnostic and FMI for the 100 000 sample chain

Figure 7. Hanson’s diagnostic and FMI for the 100 000 sample chain.

NFDiag of the Unthinned 1M Chain

This section is dedicated to evaluating the convergence of the unthinned Csignal,ℓ\mathbf{C}_{\mathrm{signal},\ell} chain of 1M samples in addition to the thinned version presented in § 5.3. Since we keep the batch size constant between the two analyses, the NF model in this section essentially updates a factor of 10 times more per training epoch, and therefore converges rapidly and stably. The results are presented below in Figure 8.

Histograms of the training loss and validation loss

Figure 8. Histograms of the training loss Lt\mathcal{L}_t and validation loss Lv\mathcal{L}_v at Epoch 6 for the NF model trained on 1M Csignal,ℓ\mathbf{C}_{\mathrm{signal},\ell} samples from our HMC sampler.

References

  1. [8]Birgé, Lucien Rozenholc, Yves 2006, ESAIM: PS, 10, 24

Paper details

vlnc:W_anm2zt6v
Version
v1 · latest
Published
Fresh — added to the Hub within the last 30 days
Added
License
CC BY 4.0
Usage

views · 0

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Mathematics

Not recorded for this paper

View statement
Looking for related papers…
Contents