Manuscript Offprint
arXiv:2610.26733Cross-Fitting for Neural Posterior Estimation
Abstract
Neural Posterior Estimation (NPE) fits an amortized conditional density estimator to a simulated training set of complete-data realizations. NPE's training objective, log-likelihood, favors posterior approximations that assign arbitrarily high density to the training points, and typical families of amortized conditional density estimators (e.g., normalizing flows, Gaussian encoders) are flexible enough to oblige. The resulting policy of extreme overconfidence translates poorly to held-out data. Early stopping and other regularizers can prevent this degeneracy, but they are limited to selecting posterior approximations along an unfavorable optimization trajectory set by in-sample residuals, where the posterior mean is underfit while the posterior variance is overfit. To avoid this trade-off, we propose Cross-Fitting NPE (CF-NPE), which uses sample splitting to separate conditional-mean estimation from the estimation of the posterior's higher moments. Using K-fold cross-fitting, CF-NPE fits K posterior-mean regressors and then fits a conditional density estimator to the resulting out-of-fold residuals. In experiments with synthetic data and in a cosmological application, CF-NPE achieves higher held-out log-likelihood than standard NPE and typically improves calibration. CF-NPE is most useful in high-dimensional, simulation-limited settings.
1 Introduction
Neural Posterior Estimation (NPE) is a widely used method of simulation-based inference [Papamakarios and Murray, 2016, Greenberg et al., 2019]. Given a prior and a simulator from which samples can be drawn, NPE trains an amortized conditional density estimator with parameters to approximate the posterior. During training, NPE maximizes the log-likelihood:
where are independent samples from the joint distribution .
The amortized conditional density estimator is often taken to be a Gaussian encoder or a normalizing flow [Papamakarios et al., 2021]. The approximators typically used, including these two, are sufficiently flexible that, without regularity conditions on the approximating family , the NPE training objective is unbounded above: at each training input , the fitted conditional density can place arbitrarily high density near , making the empirical log-likelihood arbitrarily large. Thus, very different predicted variances can achieve the same training log-likelihood, and the posterior approximation selected is determined by the regularity conditions.
The necessity of regularizers to prevent degeneracy is not unique to NPE. The unbounded-likelihood problem for densities concentrated on observations is well known [Kiefer and Wolfowitz, 1956,
Preprint.
Test trajectory
Early stopping
MSE endpoint
--- Perfect calibration
(a) Conditional-mean accuracy

(b) Posterior calibration

Figure 1: Raw per-epoch training trajectories for standard NPE (three width-256 hidden layers) on the Gaussian–Gaussian problem ( , ), shown for one seed. Left: held-out mean squared error (MSE) to the analytic posterior mean. Right: over a test set, with the expectation over evaluated analytically and averaged over 10,000 fixed test inputs.
Sec. 6]. In regression, without regularity conditions, the training data can be perfectly interpolated by regressors that perform arbitrarily poorly on held-out data.
However, for regression with neural networks, the network architecture and the optimization path of stochastic first-order optimizers act as powerful regularizers; overfitting by neural networks is “benign” or “tempered” rather than “catastrophic,” in the taxonomy of Mallinar et al. [2022]. Early stopping is still useful, but it is not what stands in the way of catastrophic validation performance.
Neural conditional density estimation is different. In NPE, overfitting is better described as catastrophic than as benign or tempered. With a Gaussian encoder, for example, finite network capacity does not prevent setting standard deviations to the smallest positive value that floating-point numbers can represent. Early stopping is left to prevent degeneracy, and thus to set the scale of the posterior approximation.
But will early stopping recover the correct posterior scale? Early stopping effectively performs a one-dimensional search along the optimizer's trajectory, identifying the epoch with the best validation-set performance. Given that the search space is restricted to this trajectory, this is a reasonable policy: maximizing validation-set log-likelihood minimizes the KL divergence from the posterior to its approximation (that is, the forward KL divergence), averaged over simulated data realizations [Ambrogioni et al., 2019].
However, the optimizer’s trajectory is an unfortunate space to search for a good approximation of the posterior. This trajectory is produced by fitting the posterior mean and scale simultaneously to the same training pairs. Because fitting the mean reduces its in-sample residuals, those residuals underestimate held-out residual error for the fitted mean. As the mean function comes to perfectly interpolate the data points, the residuals, and therefore the fitted variance, approach zero.
Figure 1 illustrates the shortcomings of this search space for a particular NPE training run. We quantify posterior calibration with the reduced chi-square statistic:
where is the dimension of the latent space, is the fitted posterior approximation with conditional mean and coordinate-wise variances , and is a generic distribution over pairs . The reduced chi-square equals one when the fitted variances match the squared errors about the fitted mean under . Here we take to be the empirical distribution of a held-out test set.
In Figure 1, posterior mean estimation improves for 337 epochs before overfitting dominates (left panel), whereas posterior calibration steadily worsens across epochs (right panel), as the posterior spread is trained in-sample with increasingly overfit means. Early stopping (based on validation log-likelihood) trades off between mean estimation and calibration, selecting epoch 278, which is optimal for both validation- and test-set log-likelihood given the search space. However, the MSE endpoint line (left panel) shows that substantially better posterior mean estimation is possible. The MSE endpoint is the held-out MSE of a network with a similar architecture trained to minimize MSE. It is lower than the NPE trajectory's MSE not only at epoch 278 but also at its minimum, epoch 337. The MSE endpoint benefits from benign overfitting, with early stopping responding solely to the quality of conditional mean estimation.
To avoid the trade-off NPE faces between the accurate estimation of the posterior's first and second moments, we propose Cross-Fitting NPE (CF-NPE). CF-NPE fits the conditional mean and residual density in separate stages using K-fold cross-fitting ( ). Stage 1 partitions the data into K folds and trains K posterior-mean regressors, each with a different fold held out. These regressors produce out-of-fold residuals, and stage 2 fits the conditional distribution of these residuals.
On three high-dimensional synthetic inference problems, CF-NPE achieves higher test log-likelihood than standard NPE ( ). Its posterior calibration, assessed by , is within a few percent of one in every case except one, where it is 1.15, whereas standard NPE's is as high as 1.51. On a strong-gravitational-lensing source-reconstruction problem, CF-NPE achieves higher test log-likelihood than standard NPE and compute-matched standard NPE mixtures ( ).
CF-NPE is most beneficial when the simulator is computationally expensive and the latent space dimension is high. If the simulator is cheap enough to draw fresh pairs at every optimizer step, the deficiency of standard NPE motivating this work is not exercised ( ).
Deep ensembles. Like us, Hermans et al. [2022] observe that NPE and other simulation-based inference methods can produce overconfident posterior approximations. However, Hermans et al. [2022] do not trace this problem to in-sample residuals. Instead, they propose that the deep ensembles method of Lakshminarayanan et al. [2017], developed for probabilistic prediction more generally, can correct NPE overconfidence. In deep ensembles, the final posterior approximation is a uniform mixture of component posterior approximations, each fitted independently using the NPE objective with different random weight initializations. The final posterior approximation is typically more dispersed than its components, so deep ensembles do indeed counteract some underdispersion, but not in a calibrated way. For example, mixing posterior approximations can improve posterior mean estimates without contracting posterior variances accordingly, resulting in underconfidence.
Heteroscedastic regression. When paired with a Gaussian encoder, NPE essentially performs heteroscedastic regression [Nix and Weigend, 1994] on the simulated training pairs. Recent methods for heteroscedastic regression with neural networks modify the joint loss or its gradient updates to avoid poor mean or variance estimates through alternating updates [Detlefsen et al., 2019], loss reweighting [ -NLL; Seitzer et al., 2022], or stop-gradient operations [Stirn et al., 2023]. These methods alter the training loss but still estimate means and scales from the same training pairs.
3 Method
To fit an amortized posterior approximation, CF-NPE first partitions the simulated training data uniformly at random into equal-sized folds. For each training pair
Algorithm 1 CF-NPE and CF-NPE-mixture.
Require: Training pairs ; number of folds ; stage-1 replicates
1: Partition uniformly at random into equal folds
2: for do
3: Fit mean networks on and average them to obtain
4: end for
5: Form the triples , with the fold of pair
6: Fit the base residual density to by maximizing Equation (2)
7: CF-NPE-mixture: Refit an additional times with different initializations and held-out residual folds
8: return Base posterior (Equation (3)) or mixture (Equation (4))
, let denote the fold containing training pair . For each fold , let and let . CF-NPE then fits an amortized posterior approximation in two stages.
Stage 1 training. For each fold , stage 1 trains a neural network regressor to predict the posterior mean of for any . The training objective uses the data subset and MSE loss, which is asymptotically minimized by the conditional expectation. Each regressor is either a single network ( ) or the average of an ensemble of networks, all trained on but with different random initializations of their weights and biases. The KM stage-1 networks may be trained sequentially or in parallel.
Stage 2 training. For each training pair , let the out-of-fold residual . Stage 2 fits a conditional density estimator using these out-of-fold residuals. The residual density is parameterized by a neural network with weights . It is trained to maximize
The residual density can be a mean-zero diagonal Gaussian, a normalizing flow, or any other conditional density family.
Alternatively, in a variant of CF-NPE that we call CF-NPE-mixture, we repeat this stage-2 training procedure K times to produce , each with a different weight initialization and a different validation fold.
Inference. At inference time, CF-NPE pairs the stage-2 residual density estimator with the mean regressor of an arbitrary fold, which we take to be fold 1 for concreteness:
Here collects the stage-1 and stage-2 parameters. In CF-NPE-mixture, a uniform mixture is used instead:
Algorithm 1 summarizes the proposed method.
3.1 The CF-NPE advantage
Intuitively, by decoupling posterior mean estimation (stage 1) from estimation of the posterior's higher-order moments (stage 2), CF-NPE avoids the pitfall of standard NPE illustrated in Figure 1. By minimizing the MSE, which recovers the conditional mean in the population limit, stage 1 attains the "MSE endpoint" line and uses the corresponding means to center the posterior approximation. The early-stopping epoch used for stage 1 (mean estimation) is not shared by stage 2. Stage 2 then fits a conditional density estimator using out-of-fold residuals. Because these residuals are produced through cross-fitting, their distribution matches that of residuals of held-out responses at the same inputs.
Some of this intuition can be formalized. Our first result examines the difference between out-of-sample and in-sample prediction error.
Proposition 3.1 (Optimism of In-Sample Prediction). Let be training pairs, with . For , let be a predicted posterior mean with finite second moment, computed by an arbitrary procedure from the training pairs and exogenous training randomness (e.g., weight initialization, fold assignment, dropout sequence, and minibatching), and let be a fresh draw from , independent of and of the training randomness. Then for each coordinate and almost every ,
The proof closely follows a derivation of the optimism of in-sample prediction error rates from Efron [2004]. All proofs appear in §A.
In standard NPE, each posterior approximation’s mean is fitted using all training points, so the covariance term in Equation (5) is non-zero and tends to grow as optimization progresses due to overfitting. In CF-NPE, in contrast, the posterior approximation mean is fitted using the folds that do not contain . Thus, the covariance term is zero, and the in-sample and out-of-sample expected squared residuals agree. Their shared value is lower-bounded by the posterior variance, as the following proposition shows.
Proposition 3.2 (Residual Second Moment). For with , write and . Then for any deterministic vector , any coordinate , and almost every ,
Thus, the cross-fitted squared residual estimates the sum of the posterior variance and the squared error of the stage-1 regressor. As the stage-1 regressor converges to , the second moment that stage 2 targets converges to the posterior variance, for almost every x.
For CF-NPE to learn a calibrated posterior approximation, however, it is not enough to avoid unwarranted optimism in the residuals used in stage 2. Because CF-NPE stage 2 is itself standard NPE applied to the residual dataset, a natural concern is that it inherits the limitations of standard NPE that motivated this work. Thankfully, the residuals, unlike the original training responses, are approximately centered at the origin—a property a Gaussian encoder can exploit by construction and normalizing flows through their initializations.
Calibration with centered Gaussians. Suppose that CF-NPE's family of posterior approximations is Gaussian with a diagonal covariance, and further that CF-NPE stage 2 fits a mean-zero Gaussian distribution to the residuals: . Then, the posterior approximation that maximizes CF-NPE's stage-2 objective is perfectly calibrated on the training set, as the next result shows.
Proposition 3.3 (Reduced Chi-Square at a Likelihood Maximum). Let be the empirical distribution , and let be a family of diagonal Gaussian conditional densities, closed under common variance rescaling with the mean fixed. If maximizes with finite objective value, then .
Hence, for CF-NPE, but not standard NPE, calibration on the training set implies calibration on test data by Proposition 3.1, which equates the expected in-sample and out-of-sample squared residuals.
Calibration with normalizing flows. Typical normalizing flows do not provide a way of centering the posterior approximation by construction. Nevertheless, there is reason to expect that they too will benefit from training with centered responses. With a centered base distribution and symmetric weight and bias initialization, both of which are the norm, a normalizing flow produces approximately mean-zero posterior approximations initially. Because the mean starts near its optimum and stays near it along the optimization path, early stopping can stop optimization as soon as the higher moments are estimated well without compromising mean-estimation quality.
4 Experiments
We benchmark several variants of CF-NPE and standard NPE with two families of amortized conditional density estimators: diagonal Gaussian encoders and neural spline flows (NSF) [Durkan et al., 2019], implemented with Zuko [Rozet et al., 2024].
Problems. We consider three classes of inference problems. The first, the Gaussian–Gaussian problem, is a hierarchical model with a 200-dimensional latent space and a 200-dimensional data space. The second, the funnel problem, is the pathological funnel from Neal [2003], with 200-dimensional latent and data spaces. The third, the mixture problem, involves a mixture of two Gaussian components, with a 20-dimensional latent space and a 40-dimensional data space. All three problems’ simulators have hyperparameters, such as latent and data dimensions, which we set to make the problems interesting: hard enough that some inference methods would struggle, but not so hard that the problem is hopeless for every method. Unless otherwise specified, we use training pairs and 1,000 test pairs. For each of 10 seeds, the same simulations are used across methods. §B.1 gives further details of each inference problem.
Metrics. Our primary metric is the held-out log-likelihood, which, as a proper scoring rule [Gneiting and Raftery, 2007], jointly assesses calibration and precision. Log-likelihood is a uniquely important metric in our benchmarking because standard NPE is our chief comparator, and in standard NPE, maximizing log-likelihood, which equivalently minimizes the expected KL divergence from the posterior to its approximation [Ambrogioni et al., 2019], is what connects the posterior approximation to the posterior. It is only because standard NPE minimizes this KL divergence that we expect standard NPE posterior approximations to be at least somewhat calibrated and to perform well on secondary metrics of posterior approximation quality.
Our secondary metrics include the MSE of the posterior mean (relative to the simulation truth) and , both of which were considered in our earlier theoretical analysis. Additional calibration metrics reported include SBC-KS [Talts et al., 2018], TARP [Lemos et al., 2023], and C2ST [Lopez-Paz and Oquab, 2017].
Hyperparameter selection. Hyperparameter tuning is critical for these benchmarks because they seek to measure network fragility due to overfitting. Thus, the results depend heavily on how the networks are tuned. We use the Optuna hyperparameter optimizer [Akiba et al., 2019] to tune all networks, searching over network depth, width, learning rate, weight-decay strength, dropout rate, and batch size. For NSF, we also search over the number of coupling transforms, spline bins, and a tail-bound parameter. We run every network with the best-performing configuration identified across 100 trials (20 trials of random search followed by refinement). Each network is re-tuned for each problem. Mixture and ensemble variants are not tuned separately but inherit the base method's hyperparameters. Unless otherwise specified, CF-NPE performs cross-fitting with K = 10 folds.
Main result. CF-NPE ( ) achieves higher test log-likelihood than standard NPE across all problems and both approximating families (Tables 1–3). The increase is consistent across seeds. While nats are difficult to interpret in absolute terms, varying the training-set size indicates the practical significance of this improvement: CF-NPE ( ) achieves higher test log-likelihood with an simulation budget than standard NPE does with simulations ( B.8).
The higher test log-likelihood reflects improved recovery of both the first and second moments of the posterior distribution, as §3.1 anticipates. MSE is lower for CF-NPE in every cell. For CF-NPE, is within a few percent of one in every cell except the funnel problem with the NSF family, where it is at most 1.15; for standard NPE it is as high as 1.51. SBC-KS, TARP, and C2ST also find better calibration for CF-NPE in most cells (§B.4).
CF-NPE uses more compute, but the difference scarcely matters in absolute terms in these experiments, as each training run takes under 10 minutes ( B.3). These experiments, unlike the application in 5, do not saturate the GPU, so CF-NPE trains all folds in parallel (using vmap in PyTorch).
Mixtures and ensembles. Deep ensembles (see §2) give standard NPE a way to better leverage parallel compute resources and trade compute for fidelity by forming a mixture of standard NPE
Software to reproduce all experiments is available from https://github.com/jeff-regier/cf-npe.
Table 1: Gaussian–Gaussian problem (). Held-out log-likelihood (nats, mean standard error over 10 seeds), (target 1), and posterior-mean MSE under each approximating family. MSE standard errors are at most 0.001, except 0.003 for Std-NPE (standard NPE) with the NSF approximation. Bold marks entries within one standard error of the best within an approximating family. The reference rows are analytic.
| Method or reference | Gaussian | NSF | ||||
|---|---|---|---|---|---|---|
| Test LL | MSE | Test LL | MSE | |||
| Prior | ||||||
| Posterior | ||||||
| Std-NPE | ||||||
| Std-NPE-mixture, | ||||||
| Std-NPE-mixture, | ||||||
| CF-NPE, | ||||||
| CF-NPE, | ||||||
| CF-NPE, | ||||||
| CF-NPE-mixture, | ||||||
Table 2: Funnel problem (). Columns as in Table 1. MSE standard errors are at most 0.006, except 0.015 for Std-NPE with the NSF approximation. The posterior row exploits the funnel's known form, which the networks are not given: conditional on , the other coordinates have Gaussian posteriors, leaving a one-dimensional integral over (§B.1). Means and standard errors are averaged over 9 seeds; one seed is excluded for each method because its test set contains a pair with , far beyond the training-data range, which dominates .
| Method or reference | Gaussian | NSF | ||||
|---|---|---|---|---|---|---|
| Test LL | MSE | Test LL | MSE | |||
| Prior | ||||||
| Posterior | ||||||
| Std-NPE | ||||||
| Std-NPE-mixture, | ||||||
| Std-NPE-mixture, | ||||||
| CF-NPE, | ||||||
| CF-NPE, | ||||||
| CF-NPE, | ||||||
| CF-NPE-mixture, | ||||||
Table 3: Mixture problem (). Columns as in Table 1. MSE standard errors are at most 0.001.
| Method or reference | Gaussian | NSF | ||||
|---|---|---|---|---|---|---|
| Test LL | MSE | Test LL | MSE | |||
| Prior | ||||||
| Posterior | ||||||
| Std-NPE | ||||||
| Std-NPE-mixture, | ||||||
| Std-NPE-mixture, | ||||||
| CF-NPE, | ||||||
| CF-NPE, | ||||||
| CF-NPE, | ||||||
| CF-NPE-mixture, | ||||||
posterior approximations trained with different weight-initialization seeds. These mixtures appear as Std-NPE-mixture in Tables 1–3, with denoting the number of ensemble members (mixture components). We set to provide approximately compute-matched counterparts to the CF-NPE variants. Standard NPE benefits substantially from mixtures in terms of test log-likelihood.
However, CF-NPE can also leverage ensembling. With , the stage-1 (mean) networks are ensembled, while stage 2, and thus the overall posterior approximation, remains a single Gaussian or NSF. The CF-NPE-mixture variant additionally ensembles stage-2 distributions, forming a uniform mixture over them. CF-NPE performance improves as increases, suggesting stage-1 fitting is sensitive to initialization (capacity is already tuned). Forming a stage-2 mixture of NSF approximators helps with the funnel and mixture problems and is otherwise neutral. With , CF-NPE outperforms the Std-NPE-mixture variants, which are roughly compute-matched.
Latent (unlensed)
Observed (lensed)
Posterior sample 1
Posterior sample 2
Posterior sample 3

Figure 2: Strong-lensing source reconstruction. From left: the true unlensed source field of one held-out example, its observed lensed image, and three posterior samples from CF-NPE-mixture with M = 3.
The mixture variants of standard NPE are overdispersed in every cell, with as low as 0.20. Forming a mixture improves mean estimation without reducing spread, creating overdispersion (as anticipated in §2). In contrast, setting with CF-NPE improves mean estimation by making the fit more robust to seed noise, without disturbing calibration. Because runtime is dominated by stage-2 fitting with the NSF posterior, and stage 1 is parallelized over both folds and replicates, increasing from 1 to 3 increases runtime by at most 5 seconds (§B.3).
Ablations. On the Gaussian–Gaussian problem, we ablate the ingredients of CF-NPE, vary the training-set size, and test alternative remedies for standard NPE. Cross-fitting is an essential ingredient: fitting stage 2 to in-fold rather than out-of-fold residuals leaves the posterior mean unchanged but makes the posterior overconfident ( ), as §3.1 predicts. A single stage-1 fit without folds or replicates is also overconfident and estimates the mean less accurately (§B.5). Log-likelihood rises monotonically with the number of folds from 2 to 16, and even outperforms standard NPE (§B.6). A substantially oversized stage-2 NSF lowers test log-likelihood but leaves within 0.01 of one (§B.7). CF-NPE outperforms standard NPE at every training-set size from to (§B.8). CF-NPE’s advantage also depends on the latent dimension: the gap is negligible at and largest at the dimension of each problem’s main experiment, though it does not grow monotonically with (§B.9). None of the alternative remedies for standard NPE closes the gap to CF-NPE. Temperature scaling corrects but recovers little log-likelihood (§B.10); -NLL and stop-gradient losses change little (§B.11); and training each Std-NPE-mixture component on a different fold split, as CF-NPE’s stage-1 networks are, raises log-likelihood, but by less than half of the mixture’s gap to CF-NPE, and leaves the mixture overdispersed (§B.12).
5 Application: Strong-Lensing Source Reconstruction
Large masses curve spacetime. Thus, distant galaxies appear sheared or distorted when massive halos known as “strong lenses” lie along the line of sight [Treu, 2010] (see Figure 2). Strong lenses are important cosmological probes for three reasons: (1) they act as magnifying lenses, revealing structure in the source plane that otherwise would be imperceptible; (2) they can show multiple images of the same background galaxy, with time delays that measure the expansion rate of the universe; and (3) the extent of the lensing can reveal the distribution of dark matter along various lines of sight. Inferring the unlensed source plane is important for these applications, but recovery is inherently probabilistic due to pixelization, shot noise, atmospheric point spread, and degeneracy (non-identifiability) between the lens and the unlensed source. Upcoming surveys will deliver on the order of lenses [Collett, 2015], prompting interest in amortized inference methods [Hezaveh et al., 2017].
We use a five-parameter lens model, a singular isothermal ellipsoid (SIE) [Kormann et al., 1994] with external shear, and use Lenstronomy [Birrer and Amara, 2018] to render -pixel observed images with Gaussian readout noise, given a source plane and lens. The latent source plane is specified as a grid of source pixels, which are drawn from a Gaussian process. The nuisance lensing parameters are sampled uniformly for each example and marginalized over during inference. We train on 10,000 pairs per seed from this data-generating process. Lenstronomy is fast, which keeps our experiments inexpensive, but it serves here as a stand-in for high-fidelity simulators such as hydrodynamical simulations of lens galaxies, which can cost over a million core-hours each.
Table 4: Strong-lensing source reconstruction with an NSF posterior, 10 seeds per method. Test log-likelihood is the median [interquartile range] over seeds. Posterior-mean MSE and are averages over seeds standard error. Runtime is the median training wall-clock time per seed, excluding simulation time, measured on an NVIDIA GeForce RTX 5090 GPU. CF-NPE rows show stage 1 + stage 2 runtime.
| Method | Test LL ↑ | MSE ↓ | Runtime (s) ↓ | |
|---|---|---|---|---|
| Std-NPE | 2.59 [-0.67, 3.40] | 1.196 ± 0.005 | 0.124 ± 0.001 | 447 |
| Std-NPE-mixture, | 13.49 [13.14, 16.27] | 0.875 ± 0.015 | 0.111 ± 0.001 | 3906 |
| Std-NPE-mixture, | 29.83 [29.43, 32.03] | 0.810 ± 0.022 | 0.104 ± 0.001 | 20834 |
| CF-NPE, | 60.05 [58.82, 63.03] | 1.025 ± 0.021 | 0.050 ± 0.001 | 3343+265 |
| CF-NPE, | 83.21 [80.27, 84.61] | 0.985 ± 0.020 | 0.043 ± 0.000 | 10009+265 |
| CF-NPE-mixture, | 88.08 [85.01, 90.26] | 0.997 ± 0.015 | 0.043 ± 0.000 | 10009+2871 |
[Richings et al., 2021]; with such simulators, the simulation budget, not training, limits the size of the training set. Simulation products are cached per seed and shared across methods; reported runtimes exclude simulation.
We apply both standard NPE and CF-NPE to these data using an NSF family of conditional density estimators. The NSF is composed of coupling layers that alternate between the two halves of a column-striped partition of the source pixels. Our encoder architecture, shared by all methods, is a residual convolutional neural network with two stride-2 stages that maps the -pixel observed image to a -pixel representation of the source plane. The network architecture has hyperparameters that enable attention layers, spatial dropout, stochastic-depth regularization, and squeeze-and-excitation, and allow variation in the depth and width of various modules. We select hyperparameters for each encoder using Optuna and list them in §C.
Results. CF-NPE delivers major improvements over standard NPE (Table 4). Every CF-NPE variant has a higher median test log-likelihood, our primary metric, than standard NPE, with non-overlapping interquartile ranges. Training CF-NPE with takes roughly an hour, whereas standard NPE takes less than 10 minutes, because CF-NPE requires training stage-1 networks. Unlike in §4, these CF-NPE networks individually saturate the GPU, so they cannot be sped up through parallelization.
The mixture variants of standard NPE provide compute-matched comparators to CF-NPE. These variants improve on the non-mixture version, providing higher test log-likelihoods. However, CF-NPE can also leverage ensembling and mixtures, and the gains from doing so stack with the gains from cross-fitting. With an ensemble of stage-1 networks per fold across folds, CF-NPE delivers a higher test log-likelihood than any standard NPE mixture tested, including the variant, which trains more networks than CF-NPE with and takes longer to train.
CF-NPE-mixture, which forms a mixture of stage-2 posterior approximations in addition to ensembling over stage-1 networks, achieves the highest test log-likelihood of all. Training the mixture adds little runtime, as most of the runtime is devoted to the stage-1 ensemble.
In standard NPE, early stopping trades off underfitting the posterior mean against overfitting the posterior variance; CF-NPE removes this trade-off. On this problem, the benefit appears as more accurate posterior means and better calibration: every CF-NPE variant has within 0.03 of one, whereas standard NPE is overconfident and the Std-NPE-mixture variants are underconfident.
Appendix §C presents further calibration metrics. SBC-KS agrees with : every CF-NPE variant scores better than every standard NPE variant. Standard NPE attains the lowest TARP KS, but TARP is difficult to interpret when, as here, the posterior is far more concentrated than the prior. TARP draws a reference point from the prior and compares its distances to the simulated latent and to the posterior draws. Two common errors can offset in this comparison: if the approximation's mean is farther from the prior mean than the exact posterior mean is, the draws tend to lie farther from the reference point than the simulated latent; if the approximation is too narrow, the simulated latent tends to lie farther away than the draws. C2ST is near 0.5 for every method and is therefore uninformative.
6 Discussion
CF-NPE corrects a problem with standard NPE that occurs when a simulated training set is reused for multiple epochs, causing the mean estimates to overfit and the in-sample residuals to become underdispersed proxies for the out-of-sample residuals. This kind of multi-epoch training is standard practice in NPE, but if simulation is cheap enough to draw fresh training pairs at each optimizer step, then in-sample and out-of-sample residuals have the same distribution, and standard NPE's defect is not exercised. Similarly, if the latent-space dimension is low relative to the number of training examples, standard NPE may not overfit the posterior means and therefore perform like CF-NPE.
Compute trade-off. CF-NPE generally requires more training time than standard NPE because it trains multiple networks. For many problems, training time is small relative to simulation time, or small in absolute terms, and thus of little consequence. Occasionally, CF-NPE can even train faster than standard NPE because the stage-1 networks are lightweight and can be trained in parallel, and decoupling mean estimation from conditional density estimation favors a lightweight stage-2 network. More typically, however, when training each network saturates the GPU, CF-NPE is approximately an order of magnitude slower than standard NPE because it trains networks. For hyperparameter selection, which can be much more expensive than training, CF-NPE can tune a single ensemble member rather than the full ensemble collectively, giving roughly the same tuning cost as standard NPE.
Sequential NPE. Our present analysis covers only single-round amortized NPE. In sequential NPE methods such as SNPE or APT [Papamakarios and Murray, 2016, Greenberg et al., 2019], each round's proposal is fixed given the previous rounds, so simulations within a round are independent. CF-NPE could replace standard NPE within each round, perhaps yielding good empirical results. However, we have not explored this possibility, as the dependence across rounds makes the entire procedure difficult to analyze, whether CF-NPE performs each round or not.
Cross-fold ensembling. CF-NPE averages M networks to estimate a posterior mean, rather than all KM stage-1 networks. At training time, restricting averaging to M networks is needed to implement cross-fitting, but at inference time, the stage-2 network has already been fit, so in principle we could average across all KM networks to get more stable mean estimates. The drawback of doing so is that improving the mean without shrinking the variance causes underconfidence, which is acceptable in some applications but not others.
Calibration with normalizing flows. The theoretical case for CF-NPE's calibration is strongest with a Gaussian encoder, whereas the analysis for normalizing flows leans more on intuition ( ). Nevertheless, CF-NPE with normalizing flows appears to be well calibrated empirically; even in an ablation study in which the normalizing flows are poorly tuned (oversized and under-regularized), CF-NPE remains nearly perfectly calibrated ( ). We would like to better understand why. The complicated training dynamics of discrete normalizing flows, as considered here, make them difficult to analyze, but continuous normalizing flows trained with flow matching [Wildberger et al., 2023] may be more amenable to analysis.
Higher standardized moments. CF-NPE separates mean (first moment) estimation from estimation of the higher moments, avoiding a trade-off between first and second moments. All the higher moments are estimated together, however, by standard NPE in stage 2, presumably entailing a tension between the second and third moments like the one that motivated this work. Nested forms of cross-fitting could potentially extend the benefits of CF-NPE to these higher moments, but at rapidly escalating computational cost. Exploring whether approximate refitting methods [e.g., Giordano et al., 2019] can recover much of that benefit at a fraction of the cost is another interesting direction for future work.
References
T. Akiba, S. Sano, T. Yanase, T. Ohta, and M. Koyama. Optuna: A next-generation hyperparameter optimization framework. In ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 2019. doi: 10.1145/3292500.3330701.
L. Ambrogioni, U. Güçlü, J. Berezutskaya, E. van den Borne, Y. Güçlütürk, M. Hinne, E. Maris, and M. van Gerven. Forward amortized inference for likelihood-free variational marginalization. In International Conference on Artificial Intelligence and Statistics, 2019. URL https://proceedings.mlr.press/v89/ambrogioni19a.html.
S. Birrer and A. Amara. lenstronomy: Multi-purpose gravitational lens modelling software package. Physics of the Dark Universe, 22:189–201, 2018. doi: 10.1016/j.dark.2018.11.002.
V. Chernozhukov, D. Chetverikov, M. Demirer, E. Duflo, C. Hansen, W. Newey, and J. Robins. Double/debiased machine learning for treatment and structural parameters. The Econometrics Journal, 21(1):C1–C68, 2018. doi: 10.1111/ectj.12097.
T. E. Collett. The population of galaxy–galaxy strong lenses in forthcoming optical imaging surveys. The Astrophysical Journal, 811(1):20, 2015. doi: 10.1088/0004-637X/811/1/20.
N. S. Detlefsen, M. Jørgensen, and S. Hauberg. Reliable training and estimation of variance networks. In Advances in Neural Information Processing Systems, 2019. URL https://proceedings.neurips.cc/paper_files/paper/2019/hash/07211688a0869d995947a8fb11b215d6-Abstract.html.
C. Durkan, A. Bekasov, I. Murray, and G. Papamakarios. Neural spline flows. In Advances in Neural Information Processing Systems, 2019. URL https://proceedings.neurips.cc/paper_files/paper/2019/hash/7ac71d433f282034e088473244df8c02-Abstract.html.
B. Efron. The jackknife, the bootstrap and other resampling plans, volume 38 of CBMS-NSF Regional Conference Series in Applied Mathematics. SIAM, 1982. doi: 10.1137/1.9781611970319.
B. Efron. The estimation of prediction error: Covariance penalties and cross-validation. Journal of the American Statistical Association, 99(467):619–632, 2004. doi: 10.1198/016214504000000692.
R. Giordano, W. Stephenson, R. Liu, M. Jordan, and T. Broderick. A Swiss Army infinitesimal jackknife. In International Conference on Artificial Intelligence and Statistics, 2019. URL https://proceedings.mlr.press/v89/giordano19a.html.
T. Gneiting and A. E. Raftery. Strictly proper scoring rules, prediction, and estimation. Journal of the American Statistical Association, 102(477):359–378, 2007. doi: 10.1198/016214506000001437.
D. S. Greenberg, M. Nonnenmacher, and J. H. Macke. Automatic posterior transformation for likelihood-free inference. In International Conference on Machine Learning, 2019. URL https://proceedings.mlr.press/v97/greenberg19a.html.
C. Guo, G. Pleiss, Y. Sun, and K. Q. Weinberger. On calibration of modern neural networks. In International Conference on Machine Learning, 2017. URL https://proceedings.mlr.press/v70/guo17a.html.
J. Hermans, A. Delaunoy, F. Rozet, A. Wehenkel, V. Begy, and G. Louppe. A trust crisis in simulation-based inference? Your posterior approximations can be unfaithful. Transactions on Machine Learning Research, 2022. URL https://openreview.net/forum?id=LHAbHkt6Aq.
Y. D. Hezaveh, L. Perreault Levasseur, and P. J. Marshall. Fast automated analysis of strong gravitational lenses with convolutional neural networks. Nature, 548(7669):555–557, 2017. doi:10.1038/nature23463.
J. Kiefer and J. Wolfowitz. Consistency of the maximum likelihood estimator in the presence of infinitely many incidental parameters. The Annals of Mathematical Statistics, 27(4):887–906, 1956. doi: 10.1214/aoms/1177728066.
R. Kormann, P. Schneider, and M. Bartelmann. Isothermal elliptical gravitational lens models. Astronomy & Astrophysics, 284:285–299, 1994. URL https://articles.adsabs.harvard.edu/pdf/1994A%26A...284..285K.
B. Lakshminarayanan, A. Pritzel, and C. Blundell. Simple and scalable predictive uncertainty estimation using deep ensembles. In Advances in Neural Information Processing Systems, 2017. URL https://proceedings.neurips.cc/paper_files/paper/2017/hash/9ef2ed4b7fd2c810847ffa5fa85bce38-Abstract.html.
P. Lemos, A. Coogan, Y. Hezaveh, and L. Perreault-Levasseur. Sampling-based accuracy testing of posterior estimators for general inference. In International Conference on Machine Learning, 2023. URL https://proceedings.mlr.press/v202/lemos23a.html.
D. Lopez-Paz and M. Oquab. Revisiting classifier two-sample tests. In International Conference on Learning Representations, 2017. URL https://openreview.net/forum?id=SJkXfE5xx.
J.-M. Lueckmann, J. Boelts, D. S. Greenberg, P. J. Gonçalves, and J. H. Macke. Benchmarking simulation-based inference. In International Conference on Artificial Intelligence and Statistics, 2021. URL https://proceedings.mlr.press/v130/lueckmann21a.html.
N. Mallinar, J. B. Simon, A. Abedsoltan, P. Pandit, M. Belkin, and P. Nakkiran. Benign, tempered, or catastrophic: Toward a refined taxonomy of overfitting. In Advances in Neural Information Processing Systems, 2022. doi: 10.52202/068431-0087.
R. M. Neal. Slice sampling. The Annals of Statistics, 31(3):705–767, 2003. doi: 10.1214/aos/1056562461.
D. A. Nix and A. S. Weigend. Estimating the mean and variance of the target probability distribution. In IEEE International Conference on Neural Networks, 1994. doi: 10.1109/ICNN.1994.374138.
G. Papamakarios and I. Murray. Fast -free inference of simulation models with Bayesian conditional density estimation. In Advances in Neural Information Processing Systems, 2016. URL https://proceedings.neurips.cc/paper_files/paper/2016/hash/6aca97005c68f1206823815f66102863-Abstract.html.
G. Papamakarios, E. Nalisnick, D. J. Rezende, S. Mohamed, and B. Lakshminarayanan. Normalizing flows for probabilistic modeling and inference. Journal of Machine Learning Research, 22(57):1–64, 2021. URL https://jmlr.org/papers/v22/19-1028.html.
M. H. Quenouille. Approximate tests of correlation in time-series. Journal of the Royal Statistical Society: Series B (Methodological), 11(1):68–84, 1949. doi: 10.1111/j.2517-6161.1949.tb00023.x.
J. Richings, C. Frenk, A. Jenkins, A. Robertson, and M. Schaller. A high-resolution cosmological simulation of a strong gravitational lens. Monthly Notices of the Royal Astronomical Society, 501(3):4657–4668, 2021. doi: 10.1093/mnras/staa4013.
F. Rozet, F. Divo, and S. Schnake. probabilists/zuko: Zuko 1.1.0, Jan. 2024. URL https://doi.org/10.5281/zenodo.10571785.
M. Seitzer, A. Tavakoli, D. Antić, and G. Martius. On the pitfalls of heteroscedastic uncertainty estimation with probabilistic neural networks. In International Conference on Learning Representations, 2022. URL https://openreview.net/forum?id=aP0pXlnV1T.
A. Stirn, H. Wessels, M. Schertzer, L. Pereira, N. E. Sanjana, and D. A. Knowles. Faithful heteroscedastic regression with neural networks. In International Conference on Artificial Intelligence and Statistics, 2023. URL https://proceedings.mlr.press/v206/stirn23a.html.
S. Talts, M. Betancourt, D. Simpson, A. Vehtari, and A. Gelman. Validating Bayesian inference algorithms with simulation-based calibration. arXiv:1804.06788 [stat.ME], 2018. URL https://arxiv.org/abs/1804.06788.
T. Treu. Strong lensing by galaxies. Annual Review of Astronomy and Astrophysics, 48(1):87–125, 2010. doi: 10.1146/annurev-astro-081309-130924.
J. Wildberger, M. Dax, S. Buchholz, S. Green, J. H. Macke, and B. Schölkopf. Flow matching for scalable simulation-based inference. In Advances in Neural Information Processing Systems, volume 36, pages 16837–16864, 2023. doi: 10.52202/075280-0737.
Appendices
A Calibration of CF-NPE
Proposition 3.1 (Optimism of In-Sample Prediction). Let be training pairs, with . For , let be a predicted posterior mean with finite second moment, computed by an arbitrary procedure from the training pairs and exogenous training randomness (e.g., weight initialization, fold assignment, dropout sequence, and minibatching), and let be a fresh draw from , independent of and of the training randomness. Then for each coordinate and almost every ,
Proof. Condition on and let , , and , with . The squared residuals satisfy
and
Because the second moments are finite, all the expectations below exist. Given , is independent of with mean zero, so . Because the pairs are independent, , so and have the same conditional law and hence equal conditional second moments. Subtracting the two expansions and taking conditional expectations gives
the last step because and is fixed given . Negating both sides gives Equation (5).
Proposition 3.2 (Residual Second Moment). For with , write and . Then for any deterministic vector , any coordinate , and almost every ,
Proof. Fix x with , which holds for almost every x. Adding and subtracting inside the square gives
Taking the conditional expectation given x, the first term becomes , the cross term vanishes because and c is fixed, and the last term is unchanged. This is Equation (6).
Proposition 3.3 (Reduced Chi-Square at a Likelihood Maximum). Let be the empirical distribution , and let be a family of diagonal Gaussian conditional densities, closed under common variance rescaling with the mean fixed. If maximizes with finite objective value, then .
Proof. For , let denote with every variance multiplied by and the mean unchanged. By assumption, . Write . Rescaling the variances gives . Taking expectations under yields
Since maximizes the training log-likelihood over , the derivative of Equation (7) with respect to vanishes at . Thus , giving the result.
B Synthetic Experiments
B.1 Generative Models
We study three problems: the Gaussian–Gaussian problem, the funnel problem, and the mixture problem. Unless stated otherwise, every experiment uses training simulations, a test set of 1,000 simulations, the Gaussian and NSF posterior approximations, 100 training epochs, the hyperparameters selected in §B.2, and folds for CF-NPE. Each method is run with 10 seeds, and tables report the mean ± standard error over seeds. Each later study states only the settings it changes.
Gaussian–Gaussian problem. This conjugate model is a standard benchmark in the simulation-based inference literature [e.g., Lueckmann et al., 2021], in which prior, likelihood, and posterior are all Gaussian. It has . The generative model is
giving posterior .
Funnel problem. The funnel problem has a non-Gaussian posterior whose conditional scale varies by orders of magnitude. It has . The generative model is
with . Given , the coordinates ( ) have independent Gaussian posteriors, so the posterior reduces to a one-dimensional integral over , which we evaluate numerically on a grid. We report the resulting Bayes-optimal test log-likelihood and posterior-mean MSE, averaged over simulated pairs (Monte Carlo standard errors below 0.01), and the expected log-likelihood of the prior, .
Mixture problem. The mixture problem has a two-component Gaussian observation model. It has and . The generative model is
with entries drawn once and then fixed across methods and experimental seeds within each dimension, mode separation , and . Because the prior and each likelihood component are Gaussian and linear in , the posterior is a two-component Gaussian mixture available in closed form, so we report the Bayes-optimal test log-likelihood as a reference. We also report the expected log-likelihood under the prior. The posterior covariance is non-diagonal, which our diagonal Gaussian posterior approximation cannot represent.
B.2 Hyperparameter Search Spaces and Selected Settings
Table B.1 gives the shared hyperparameter search spaces. Tables B.2–B.4 report the selected settings for the three problems. Each problem has one CF-NPE stage-1 mean-network configuration shared by the Gaussian and NSF families, and separately selected Std-NPE and CF-NPE stage-2 configurations for each family.
The fitted stage-1 networks are held fixed during stage-2 tuning. Within each problem and approximating family, the CF-NPE configurations share the selected stage-1 and stage-2 hyperparameters and differ only in fold count, replicate count, or whether stage 2 forms a mixture (CF-NPE-mixture).
Table B.1: Hyperparameter search spaces for the three problems. Intervals marked log are sampled log-uniformly.
| hyperparameter | Std-NPE / CF-NPE stage 1 | CF-NPE stage 2 |
|---|---|---|
| learning rate | \log | \log |
| weight decay | \log | \log |
| width | {64, 128, 256, 512} | {64, 128, 256} |
| depth | {1, 2, 3} | {1, 2, 3} |
| dropout | [0, 0.5] | [0, 0.5] |
| batch size | {64, 128, 256} | {64, 128, 256} |
| coupling transforms (NSF) | {2, 3, 5} | {2, 3, 5} |
| spline bins (NSF) | {8, 16} | {8, 16} |
| tail bound (NSF) | {3, 5, 7} | {3, 5, 7} |
B.3 Training Time
Table B.5: Training time in seconds for one seed, by problem, method, and approximating family, timed after a GPU warm-up so that one-time startup costs are excluded. CF-NPE rows show stage 1 + stage 2 runtimes. Timings were measured on one NVIDIA GeForce RTX 5090 GPU.
| Method | Gaussian–Gaussian | Funnel | Mixture | |||
|---|---|---|---|---|---|---|
| Gaussian | NSF | Gaussian | NSF | Gaussian | NSF | |
| Std-NPE | 2 | 83 | 9 | 131 | 8 | 22 |
| Std-NPE-mixture, | 3 | 133 | 14 | 220 | 11 | 27 |
| Std-NPE-mixture, | 3 | 344 | 27 | 565 | 12 | 66 |
| CF-NPE, | 5+3 | 5+75 | 9+9 | 9+135 | 9+5 | 9+72 |
| CF-NPE, | 5+3 | 5+68 | 8+9 | 8+134 | 9+5 | 9+72 |
| CF-NPE, | 6+3 | 6+67 | 22+9 | 22+136 | 9+5 | 9+71 |
| CF-NPE-mixture, | 5+4 | 5+143 | 8+13 | 8+196 | 9+7 | 9+93 |
B.4 Calibration Diagnostics
For , we estimate the posterior mean and coordinate-wise variance from 500 posterior samples and average the standardized squared errors over test pairs and coordinates. Simulation-based calibration (SBC) [Talts et al., 2018] uses 256 posterior samples per test pair; the reported SBC-KS is the Kolmogorov–Smirnov distance from uniformity of the normalized marginal ranks, pooled over pairs and coordinates. TARP [Lemos et al., 2023] evaluates joint coverage using 250 posterior samples and 10 prior-drawn reference points per test pair; the reported TARP KS is the Kolmogorov–Smirnov distance from uniformity of its coverage statistic, the largest gap between the empirical coverage curve and the nominal-coverage diagonal. The classifier two-sample test (C2ST) [Lopez-Paz and Oquab, 2017] simulates 10,000 new pairs (z, x) and pairs each x with one draw from the posterior approximation. A two-layer, width-256 classifier is trained for 30 epochs on half of the pairs to tell simulated z from posterior draws and is scored on the other half. Its target accuracy is 0.5. Table B.6 reports the results.
Table B.2: Selected hyperparameters for the Gaussian–Gaussian problem.
| hyperparameter | CF-NPE stage 1 both families | Gaussian | NSF | ||
|---|---|---|---|---|---|
| Std-NPE | CF-NPE stage 2 | Std-NPE | CF-NPE stage 2 | ||
| learning rate | |||||
| weight decay | |||||
| width | 256 | 256 | 128 | 256 | 128 |
| depth | 1 | 1 | 3 | 1 | 2 |
| dropout | 0.00100 | 0.0151 | 0.476 | 0.0402 | 0.418 |
| batch size | 128 | 128 | 256 | 64 | 64 |
| coupling transforms | — | — | — | 5 | 2 |
| spline bins | — | — | — | 16 | 16 |
| tail bound | — | — | — | 7 | 7 |
Table B.3: Selected hyperparameters for the funnel problem.
| hyperparameter | CF-NPE stage 1 both families | Gaussian | NSF | ||
|---|---|---|---|---|---|
| Std-NPE | CF-NPE stage 2 | Std-NPE | CF-NPE stage 2 | ||
| learning rate | |||||
| weight decay | |||||
| width | 512 | 512 | 256 | 256 | 128 |
| depth | 1 | 3 | 3 | 1 | 1 |
| dropout | 0.00440 | 0.00423 | 0.218 | 0.00507 | 0.477 |
| batch size | 64 | 64 | 64 | 64 | 64 |
| coupling transforms | — | — | — | 5 | 5 |
| spline bins | — | — | — | 8 | 8 |
| tail bound | — | — | — | 7 | 5 |
Table B.4: Selected hyperparameters for the mixture problem.
| hyperparameter | CF-NPE stage 1 both families | Gaussian | NSF | ||
|---|---|---|---|---|---|
| Std-NPE | CF-NPE stage 2 | Std-NPE | CF-NPE stage 2 | ||
| learning rate | |||||
| weight decay | |||||
| width | 256 | 64 | 64 | 64 | 256 |
| depth | 1 | 1 | 3 | 1 | 3 |
| dropout | 0.00115 | 0.00950 | 0.318 | 0.0200 | 0.450 |
| batch size | 64 | 128 | 256 | 64 | 128 |
| coupling transforms | — | — | — | 2 | 5 |
| spline bins | — | — | — | 16 | 16 |
| tail bound | — | — | — | 5 | 5 |
Table B.6: Calibration diagnostics for the three problems by stage-1 replicate count.
| Method | Gaussian | NSF | ||||
|---|---|---|---|---|---|---|
| SBC-KS ↓ | TARP KS ↓ | C2ST (→ 0.5) | SBC-KS ↓ | TARP KS ↓ | C2ST (→ 0.5) | |
| Gaussian-Gaussian problem | ||||||
| Std-NPE | 0.009 ± 0.000 | 0.239 ± 0.003 | 0.581 ± 0.002 | 0.005 ± 0.001 | 0.415 ± 0.007 | 0.827 ± 0.024 |
| CF-NPE, M=1 | 0.002 ± 0.000 | 0.017 ± 0.002 | 0.557 ± 0.002 | 0.002 ± 0.000 | 0.022 ± 0.002 | 0.556 ± 0.002 |
| CF-NPE, M=3 | 0.002 ± 0.000 | 0.106 ± 0.004 | 0.554 ± 0.001 | 0.002 ± 0.000 | 0.017 ± 0.001 | 0.553 ± 0.002 |
| Funnel problem | ||||||
| Std-NPE | 0.022 ± 0.002 | 0.311 ± 0.006 | 0.872 ± 0.004 | 0.005 ± 0.001 | 0.221 ± 0.015 | 0.973 ± 0.002 |
| CF-NPE, M=1 | 0.005 ± 0.001 | 0.347 ± 0.004 | 0.547 ± 0.002 | 0.012 ± 0.001 | 0.183 ± 0.004 | 0.531 ± 0.003 |
| CF-NPE, M=3 | 0.005 ± 0.001 | 0.450 ± 0.004 | 0.541 ± 0.001 | 0.018 ± 0.000 | 0.203 ± 0.005 | 0.514 ± 0.002 |
| Mixture problem | ||||||
| Std-NPE | 0.007 ± 0.001 | 0.019 ± 0.002 | 0.797 ± 0.003 | 0.023 ± 0.001 | 0.058 ± 0.003 | 0.688 ± 0.003 |
| CF-NPE, M=1 | 0.007 ± 0.001 | 0.023 ± 0.002 | 0.781 ± 0.004 | 0.007 ± 0.001 | 0.024 ± 0.004 | 0.530 ± 0.002 |
| CF-NPE, M=3 | 0.008 ± 0.001 | 0.017 ± 0.002 | 0.764 ± 0.005 | 0.012 ± 0.002 | 0.022 ± 0.002 | 0.528 ± 0.002 |
B.5 Cross-Fitting Ablations
On the Gaussian–Gaussian problem, we remove ingredients of CF-NPE (M = 3) one at a time (Table B.7). The in-fold residuals variant fits stage 2 to in-sample residuals: pairs in fold k take their mean from the networks of fold (modulo K), which are trained on them. Single mean fit replaces the folds and replicates with one stage-1 network, trained on 80% of the training set and early-stopped on the other 20%; stage 2 is fit to its in-sample residuals on the same 80%.
The in-fold residuals variant leaves the posterior mean unchanged but makes the posterior overconfident, as §3.1 predicts. The single mean fit is also overconfident and has higher posterior-mean MSE.
Table B.7: Cross-fitting ablations on the Gaussian–Gaussian problem, for each approximating family. MSE standard errors are at most 0.001. The CF-NPE, M = 3 rows are the runs reported in Table 1.
| Method | LL ↑ | MSE ↓ | SBC-KS ↓ | TARP KS ↓ | C2ST (→ 0.5) | |
|---|---|---|---|---|---|---|
| Gaussian | ||||||
| CF-NPE, M=3 | -128.42 ± 0.10 | 0.993 ± 0.002 | 0.212 | 0.002 ± 0.000 | 0.106 ± 0.004 | 0.554 ± 0.001 |
| in-fold residuals | -129.45 ± 0.12 | 1.150 ± 0.002 | 0.212 | 0.017 ± 0.000 | 0.240 ± 0.004 | 0.563 ± 0.002 |
| single mean fit | -136.01 ± 0.14 | 1.094 ± 0.009 | 0.227 | 0.011 ± 0.001 | 0.082 ± 0.007 | 0.566 ± 0.001 |
| NSF | ||||||
| CF-NPE, M=3 | -128.31 ± 0.10 | 1.000 ± 0.001 | 0.212 | 0.002 ± 0.000 | 0.017 ± 0.001 | 0.553 ± 0.002 |
| in-fold residuals | -129.55 ± 0.10 | 1.164 ± 0.001 | 0.212 | 0.019 ± 0.000 | 0.135 ± 0.003 | 0.560 ± 0.001 |
| single mean fit | -136.91 ± 0.11 | 1.188 ± 0.002 | 0.227 | 0.024 ± 0.001 | 0.114 ± 0.007 | 0.575 ± 0.005 |
B.6 Fold Count
Increasing the number of folds grows the effective training set used for conditional mean estimation. Table B.8 reports that mean test log-likelihood rises with , with diminishing gains as grows. Even the smallest tested fold count achieves higher test log-likelihood than standard NPE.
Table B.8: Fold-count scaling for CF-NPE on the Gaussian–Gaussian problem (Gaussian approximation, M = 3): test log-likelihood vs. number of folds K.
| K | test log-likelihood |
|---|---|
| 2 | |
| 4 | |
| 8 | |
| 10 | |
| 16 |
B.7 Oversized Stage-2 Flow Ablation
How sensitive is CF-NPE to the size of its stage-2 normalizing flow? On the Gaussian–Gaussian problem with , we replace the tuned stage-2 NSF with three larger flows, keeping stage 1 fixed. +Width increases the width, the number of coupling transforms, and the number of spline bins, and lowers the learning rate. +Depth adds two hidden layers to +Width. –Regularization removes dropout and weight decay from +Depth. Each flow uses early stopping on validation log-likelihood. Table B.9 reports the varied hyperparameters and results, using the diagnostics of §B.4. These oversized flows lose a little test log-likelihood and have somewhat worse SBC, TARP, and C2ST diagnostics than the tuned flow, but their stays close to one.
Table B.9: Stage-2 NSF configurations for CF-NPE () on the Gaussian–Gaussian problem: the hyperparameters that differ across configurations (top), the epoch selected by early stopping out of 100 (middle), and the calibration diagnostics (bottom). The Tuned column's hyperparameters repeat Table B.2, and its diagnostics repeat Tables 1 and B.6.
| Tuned | +Width | +Depth | –Regularization | |
|---|---|---|---|---|
| learning rate | ||||
| weight decay | ||||
| width | 128 | 1024 | 1024 | 1024 |
| depth | 2 | 2 | 5 | 5 |
| dropout | 0.418 | 0.418 | 0.418 | 0 |
| coupling transforms | 2 | 8 | 8 | 8 |
| spline bins | 16 | 32 | 32 | 32 |
| best epoch | ||||
| LL | ||||
| SBC-KS | ||||
| TARP KS | ||||
| C2ST () |
B.8 Training-Set-Size Scaling
On the Gaussian–Gaussian problem, Table B.10 compares standard NPE and CF-NPE across a variety of training-set sizes. Standard NPE is tuned separately at each , whereas CF-NPE reuses the hyperparameters selected at . CF-NPE has a higher mean test log-likelihood at every tested .
Table B.10: Training-set-size scaling on the Gaussian–Gaussian problem (Gaussian approximation): test log-likelihood vs. for standard NPE and CF-NPE ().
| Std-NPE | CF-NPE () | |
|---|---|---|
| 1,000 | ||
| 3,000 | ||
| 10,000 | ||
| 30,000 | ||
| 100,000 |
B.9 Dimension Sweeps
We vary the latent dimension of each problem, re-tuning standard NPE and CF-NPE stage 2 at each dimension by the procedure of §B.2; CF-NPE stage 1 keeps the configuration selected for the problem's main experiment (Tables B.11–B.13).
Table B.11: Dimension sweep for the Gaussian–Gaussian problem (Gaussian approximation): test log-likelihood, the difference in test log-likelihood between CF-NPE and standard NPE (computed within each seed, then averaged), and the expected log-likelihoods of the prior and the exact posterior.
| Std-NPE | CF-NPE | (CF–std) | Prior | Posterior | |
|---|---|---|---|---|---|
| 2 | |||||
| 10 | |||||
| 50 | |||||
| 100 | |||||
| 200 |
Table B.12: Dimension sweep for the funnel problem (NSF approximation): test log-likelihood, the difference in test log-likelihood between CF-NPE and standard NPE (computed within each seed, then averaged), and the expected log-likelihoods of the prior and the exact posterior.
| Std-NPE | CF-NPE | (CF–std) | Prior | Posterior | |
|---|---|---|---|---|---|
| 2 | |||||
| 10 | |||||
| 20 | |||||
| 50 |
Table B.13: Dimension sweep for the mixture problem (NSF approximation): test log-likelihood, the difference in test log-likelihood between CF-NPE and standard NPE (computed within each seed, then averaged), and the expected log-likelihoods of the prior and the exact posterior.
| Std-NPE | CF-NPE | (CF–std) | Prior | Posterior | |
|---|---|---|---|---|---|
| 2 | |||||
| 10 | |||||
| 20 | |||||
| 50 |
B.10 Temperature-Scaling Baseline
Adapting temperature scaling from classification [Guo et al., 2017], we fit a single scalar on 10,000 newly simulated validation pairs after training and multiply every predicted standard deviation by . On the Gaussian–Gaussian problem, temperature scaling brings close to one but recovers only a small part of the test-log-likelihood gap between standard NPE and CF-NPE (Table B.14). It leaves the posterior-mean MSE unchanged by construction, so the MSE remains higher than CF-NPE's.
Table B.14: Temperature-scaling baseline on the Gaussian–Gaussian problem: test log-likelihood, , and posterior-mean MSE. MSE standard errors are at most 0.001. The Std-NPE and CF-NPE, rows are repeated from Table 1.
| Method | Test LL ↑ | MSE ↓ | |
|---|---|---|---|
| Std-NPE | |||
| Std-NPE + temperature scaling | |||
| CF-NPE, |
B.11 Alternative-Loss Baselines
Heteroscedastic-regression losses modify the Gaussian negative log-likelihood (NLL) so that the predicted variance does not slow the fit of the mean, but they still fit the variance to residuals of a mean trained on the same pairs. Does changing the loss alone remove standard NPE's overconfidence? We train standard NPE with two such losses (Table B.15). Both keep the Gaussian approximation and the hyperparameters selected for standard NPE on the Gaussian–Gaussian problem. -NLL with , following Seitzer et al. [2022], multiplies each coordinate's NLL by that coordinate's predicted variance, treated as a constant. Stop-gradient, adapted from Stirn et al. [2023], adds an MSE loss for the mean to a Gaussian NLL in which the mean is treated as a constant; the variance's gradients still update the encoder that the mean and variance outputs share. -NLL raises test log-likelihood by about 0.9 nats, under a tenth of standard NPE's gap to CF-NPE, and neither loss changes or posterior-mean MSE appreciably. In particular, both remain overconfident, like CF-NPE with in-fold residuals (B.5).
Table B.15: Alternative-loss baselines on the Gaussian–Gaussian problem: test log-likelihood, , and posterior-mean MSE. MSE standard errors are at most 0.001. The Std-NPE and CF-NPE, rows are repeated from Table 1.
| Method | Test LL ↑ | MSE ↓ | |
|---|---|---|---|
| Std-NPE | -141.30 ± 0.11 | 1.095 ± 0.001 | 0.234 |
| Std-NPE + β-NLL | -140.41 ± 0.11 | 1.082 ± 0.001 | 0.233 |
| Std-NPE + stop-gradient | -141.09 ± 0.12 | 1.090 ± 0.001 | 0.235 |
| CF-NPE, M=3 | -128.42 ± 0.10 | 0.993 ± 0.002 | 0.212 |
B.12 Split-by-Fold Mixture Baseline
Does validating each Std-NPE-mixture component on its own fold, as CF-NPE's stage-1 networks are validated, close the gap to CF-NPE? On the Gaussian–Gaussian problem, split by fold early-stops component k of the Std-NPE-mixture on fold k and trains it on the other nine folds, instead of giving every component the same split (Table B.16). Splitting by fold raises the test log-likelihood of Std-NPE-mixture, though not to the level of CF-NPE, and leaves its unchanged.
Table B.16: Split-by-fold mixture baseline on the Gaussian–Gaussian problem, for each approximating family. MSE standard errors are at most 0.002. The Std-NPE-mixture, and CF-NPE, rows are the runs reported in Table 1.
| Method | LL ↑ | MSE ↓ | SBC-KS ↓ | TARP KS ↓ | C2ST (→ 0.5) | |
|---|---|---|---|---|---|---|
| Gaussian | ||||||
| Std-NPE-mixture, | -134.79 ± 0.12 | 0.890 ± 0.001 | 0.212 | 0.016 ± 0.000 | 0.238 ± 0.002 | 0.571 ± 0.001 |
| split by fold | -133.34 ± 0.11 | 0.879 ± 0.001 | 0.211 | 0.017 ± 0.000 | 0.233 ± 0.003 | 0.560 ± 0.001 |
| CF-NPE, M=3 | -128.42 ± 0.10 | 0.993 ± 0.002 | 0.212 | 0.002 ± 0.000 | 0.106 ± 0.004 | 0.554 ± 0.001 |
| NSF | ||||||
| Std-NPE-mixture, | -159.24 ± 0.27 | 0.677 ± 0.002 | 0.251 | 0.041 ± 0.000 | 0.417 ± 0.003 | 0.735 ± 0.005 |
| split by fold | -154.88 ± 0.29 | 0.684 ± 0.001 | 0.246 | 0.040 ± 0.000 | 0.436 ± 0.004 | 0.721 ± 0.002 |
| CF-NPE, M=3 | -128.31 ± 0.10 | 1.000 ± 0.001 | 0.212 | 0.002 ± 0.000 | 0.017 ± 0.001 | 0.553 ± 0.002 |
C Strong-Lensing Source Reconstruction: Implementation Details
Forward simulator. The latent z is a synthetic source-plane field on a field of view (d = 256). The source field is drawn from a Gaussian process on the source grid with a radial basis function kernel whose length scale is one source pixel. The resulting pixels are spatially correlated, and each has a unit-variance Gaussian marginal. The lens consists of a singular isothermal ellipsoid [Kormann et al., 1994] with parameters and an external shear , sampled uniformly and independently per pair. Given the lens parameters, the image-plane value at pixel is the source-field value at the deflected position , computed by bilinear interpolation on the source grid using the closed-form SIE deflection [Birrer and Amara, 2018]. The image is rendered on a grid with pixels (a field of view), convolved with a Gaussian point-spread function with full width at half maximum , and corrupted with Gaussian readout noise ( ).
Table C.1: Strong lensing (): selected hyperparameters. A dash denotes a setting that does not apply.
| hyperparameter | Std-NPE | CF-NPE stage 1 | CF-NPE stage 2 |
|---|---|---|---|
| learning rate | |||
| weight decay | |||
| batch size | 128 | 64 | 128 |
| encoder base channels | 64 | 32 | 32 |
| encoder activation | GELU | SiLU | SiLU |
| encoder blocks per stage | 2 | 4 | 4 |
| encoder dropout | 0.1 | 0 | 0 |
| encoder stochastic depth | 0 | 0.2 | 0.2 |
| encoder group-norm groups | 32 | 8 | 8 |
| encoder squeeze-and-excitation | no | yes | yes |
| dropout after the encoder | — | 0.3 | — |
| coupling transforms | 3 | — | 3 |
| spline bins | 8 | — | 8 |
| tail bound | 5 | — | 5 |
| coupling partition | column stripes | — | column stripes |
| conditioner width | 64 | — | 64 |
| conditioner blocks | 6 | — | 6 |
| conditioner attention layers | 2 | — | 2 |
| conditioner dropout | 0.1 | — | 0.1 |
| conditioner stochastic depth | 0.1 | — | 0.1 |
| stage-2 encoder channels | — | — | 64 |
| stage-1-mean channels | — | — | 8 |
Networks. Every method receives only the lensed image; the lens parameters are not provided. The image is transformed by asinh and processed by a residual convolutional encoder with two stride-2 stages that reduce the spatial resolution from to the source grid. Its base channels double at each stage, and it uses group normalization and spatial dropout after each residual stage. The CF-NPE stage-1 conditional-mean network maps this feature map to the predicted mean at the fixed resolution with 16 residual blocks of width 256, one self-attention layer (4 heads), a sin/cos positional encoding, and extra channels holding the image-wide average of each feature, ending in a layer that outputs one mean per pixel.
Standard NPE and the CF-NPE stage-2 model both represent the source-grid density with a coupling-based neural spline flow. Each coupling holds half of the source pixels fixed under a spatial partition and transforms the rest with monotonic rational-quadratic splines whose per-pixel parameters come from a conditioner network: a residual network at the source-grid resolution that takes the fixed half of the latent variables (placed at their grid positions, with zeros at the pixels being transformed), the encoder feature map, and a binary mask channel. Alternating couplings transform every pixel. The stage-2 model has its own encoder and models the out-of-fold residuals, each divided by the standard deviation of its pixel's training residuals, conditional on the image and the out-of-fold stage-1 mean. It passes the stage-1 mean through two convolutions and concatenates the result with its own feature map on the source grid. At inference, residual samples are multiplied back by those standard deviations and added to the stage-1 mean.
Hyperparameter selection. Standard NPE is tuned by a 100-trial tree-structured Parzen estimator study selecting encoder and flow settings by held-out log-likelihood on a validation split at a fixed seed. CF-NPE stage 1 is tuned by held-out MSE over the encoder, the layers after the encoder, and optimizer settings. CF-NPE stage 2 is tuned by a 100-trial fixed-seed study on one fixed set of trained stage-1 networks. It searches over learning rate, weight decay, and the channel counts of the stage-2 encoder output and of the convolved stage-1 mean, selecting by held-out log-likelihood of the standardized residuals. The flow architecture is held at the standard-NPE selection and the encoder architecture at the stage-1 selection. Table C.1 lists the selected numerical settings.
Table C.2: Strong-lensing SBC and TARP diagnostics with an NSF approximation (mean standard error). C2ST is omitted because every method scores about 0.5. Log-likelihood, , and posterior-mean MSE for the same runs are in Table 4.
| Method | SBC-KS | TARP KS |
|---|---|---|
| Std-NPE | ||
| Std-NPE-mixture, | ||
| Std-NPE-mixture, | ||
| CF-NPE, | ||
| CF-NPE, | ||
| CF-NPE-mixture, |
Training and evaluation. Training uses pairs for 100 epochs with Adam. CF-NPE uses folds. All methods use 10 seeds and 1,000 test pairs. Readout noise is resampled when examples are loaded. CF-NPE, and CF-NPE-mixture, use the same trained stage-1 networks for each seed, so they differ only in stage 2. Each member of the Std-NPE-mixture trains on its own random 90% subsample of the training pairs. Runtimes were measured on a single NVIDIA GeForce RTX 5090 GPU.
Calibration. Table C.2 reports the SBC and TARP diagnostics.