Skip to content

tests: incorrect number of posterior samples #1473

Closed

Description

@vagechirkov

🐛 Bug Description

I was working on PR #1461 (Issue: #1428). I wanted to run all tests quickly (even if they fail) just to test the fixtures, so I set num_samples=10 and steps=5 for posterior sampling in test_npse_iid_inference. Everything seems to work fine for None and gaussian prior, but something weird happens for uniform.

🟢 Gaussian prior Image Image
🟢 None prior Image Image
🔴 Uniform prior Image Image

🔄 Steps to Reproduce

Run the tests:

pytest tests/linearGaussian_npse_test.py::test_npse_iid_inference

Full tests code:
DEFAULT_USE = [
    pytest.param(("ve", None), id="ve-None"),
    pytest.param(("vp", "gaussian"), id="vp-gaussian"),
]

SLOW_COMBINATIONS = [
    pytest.param(("vp", "uniform"), id="vp-uniform", marks=pytest.mark.slow),
    pytest.param(("vp", None), id="vp-None", marks=pytest.mark.slow),
    pytest.param(("ve", "gaussian"), id="ve-gaussian", marks=pytest.mark.slow),
    pytest.param(("ve", "uniform"), id="ve-uniform", marks=pytest.mark.slow),
    pytest.param(("subvp", "gaussian"), id="subvp-gaussian", marks=pytest.mark.slow),
    pytest.param(("subvp", "uniform"), id="subvp-uniform", marks=pytest.mark.slow),
    pytest.param(("subvp", None), id="subvp-None", marks=pytest.mark.slow),
]


@pytest.fixture(scope="module")
def npse_trained_model(request):
    """Module-scoped fixture that trains a score estimator for NPSE tests."""
    sde_type, prior_type = request.param
    num_dim = 2
    num_simulations = 5

    # likelihood_mean will be likelihood_shift+theta
    likelihood_shift = -1.0 * ones(num_dim)
    likelihood_cov = 0.3 * eye(num_dim)

    if prior_type == "gaussian" or (prior_type is None):
        prior_mean = zeros(num_dim)
        prior_cov = eye(num_dim)
        prior = MultivariateNormal(loc=prior_mean, covariance_matrix=prior_cov)
        prior_npse = prior if prior_type is None else None
    elif prior_type == "uniform":
        prior = BoxUniform(-2 * ones(num_dim), 2 * ones(num_dim))
        prior_npse = prior

    # This check that our method to handle "general" priors works.
    # i.e. if NPSE does not get a proper passed by the user.
    inference = NPSE(prior_npse, show_progress_bars=True, sde_type=sde_type)

    theta = prior.sample((num_simulations,))
    x = linear_gaussian(theta, likelihood_shift, likelihood_cov)

    score_estimator = inference.append_simulations(theta, x).train(
        stop_after_epochs=200
    )

    return {
        "score_estimator": score_estimator,
        "inference": inference,
        "prior": prior,
        "likelihood_shift": likelihood_shift,
        "likelihood_cov": likelihood_cov,
        "prior_mean": prior_mean
        if prior_type == "gaussian" or prior_type is None
        else None,
        "prior_cov": prior_cov
        if prior_type == "gaussian" or prior_type is None
        else None,
        "num_dim": num_dim,
        "x_o": zeros(num_dim),
        "sde_type": sde_type,
        "prior_type": prior_type,
    }



@pytest.mark.parametrize(
    "npse_trained_model",
    DEFAULT_USE + SLOW_COMBINATIONS,
    indirect=True,  # So pytest knows to pass to the fixture
)
@pytest.mark.parametrize(
    "iid_method, num_trial",
    [
        pytest.param("fnpe", 3, id="fnpe-2trials", marks=pytest.mark.slow),
        pytest.param("gauss", 3, id="gauss-6trials", marks=pytest.mark.slow),
        pytest.param("auto_gauss", 8, id="auto_gauss-8trials"),
        pytest.param(
            "auto_gauss", 16, id="auto_gauss-16trials", marks=pytest.mark.slow
        ),
        pytest.param("jac_gauss", 8, id="jac_gauss-8trials", marks=pytest.mark.slow),
    ],
)
def test_npse_iid_inference(npse_trained_model, iid_method, num_trial):
    """Test whether NPSE infers well a simple example with available ground truth."""
    num_samples = 10

    # Extract data from fixture
    score_estimator = npse_trained_model["score_estimator"]
    inference = npse_trained_model["inference"]
    prior = npse_trained_model["prior"]
    likelihood_shift = npse_trained_model["likelihood_shift"]
    likelihood_cov = npse_trained_model["likelihood_cov"]
    prior_mean = npse_trained_model["prior_mean"]
    prior_cov = npse_trained_model["prior_cov"]
    num_dim = npse_trained_model["num_dim"]
    sde_type = npse_trained_model["sde_type"]
    prior_type = npse_trained_model["prior_type"]

    x_o = zeros(num_trial, num_dim)
    posterior = inference.build_posterior(score_estimator)
    posterior.set_default_x(x_o)
    samples = posterior.sample((num_samples,), iid_method=iid_method, steps=5)

    if prior_type == "gaussian" or (prior_type is None):
        gt_posterior = true_posterior_linear_gaussian_mvn_prior(
            x_o, likelihood_shift, likelihood_cov, prior_mean, prior_cov
        )
        target_samples = gt_posterior.sample((num_samples,))
    elif prior_type == "uniform":
        target_samples = samples_true_posterior_linear_gaussian_uniform_prior(
            x_o,
            likelihood_shift,
            likelihood_cov,
            prior,  # type: ignore
        )

    # Compute the c2st and assert it is near chance level of 0.5.
    # Some degradation is expected, also because posterior get tighter which
    # usually makes the c2st worse.
    check_c2st(
        samples,
        target_samples,
        alg=f"npse-{sde_type}-{prior_type}-{num_dim}-{iid_method}-{num_trial}iid-trials",
        tol=0.05 * min(num_trial, 8),
    )

Activity

  1. added
    bug
    on Mar 18, 2025
  2. vagechirkov commented on Mar 18, 2025

    @vagechirkov
    CollaboratorAuthor
  3. changed the title [-]Incorrect number of posterior samples[/-] [+]tests: incorrect number of posterior samples[/+] on Mar 18, 2025
  4. added
    tests
    on Mar 18, 2025
  5. vagechirkov commented on Mar 21, 2025

    @vagechirkov
    CollaboratorAuthor

    I think to reproduce this problem, one can try to simply run sampling with a very low number of samples and the uniform prior. It may just be a sampling logging bug.

  6. added
    hackathon
    beginner friendly
    on Jan 20, 2026
  7. vamshi567bh commented on Feb 13, 2026

    @vamshi567bh

    @janfb can I take this

  8. janfb commented on Feb 21, 2026

    @janfb
    Contributor

    @BharathC0 sorry for the late reply! Great, have you reproduced the error locally? And what would be your suggest for fixing this?

  9. Jocho-Smith commented on Feb 27, 2026

    @Jocho-Smith
    Contributor

    Hey everyone, I want to work on this issue. @manuelgloeckler confirmed it is fair if I do so now.

    @BharathC0 if you still want to join in, I'm sure we can collaborate on it somehow.

  10. manuelgloeckler commented on Feb 27, 2026

    @manuelgloeckler
    Contributor

    Sorry @BharathC0 but I will reassign this issue to @Jocho-Smith, given that its already some time passed without an PR and you are already involved in another "good-first-issue". Hope that fine :)

  11. Jocho-Smith commented on Mar 3, 2026

    @Jocho-Smith
    Contributor

    I'm not sure if I can reproduce the error. Here is the code that should reproduce it to my current knowledge:

    import torch
    from sbi.inference import NPSE
    from sbi.utils import BoxUniform
    from sbi.simulators import linear_gaussian
    
    num_dim = 1
    likelihood_shift = -1.0 * torch.ones(num_dim)
    likelihood_cov = 0.3 * torch.eye(num_dim)
    
    # Uniform prior
    prior = BoxUniform(-2 * torch.ones(num_dim), 2 * torch.ones(num_dim))
    
    # NPSE inference with VP SDE
    inference = NPSE(prior, sde_type="vp")
    
    # Tiny dataset for fast reproduction
    theta = prior.sample((5,))
    x = linear_gaussian(theta, likelihood_shift, likelihood_cov)
    inference.append_simulations(theta, x).train(stop_after_epochs=50)
    
    # Build posterior (do not pass prior)
    posterior = inference.build_posterior()
    
    # Set default context x
    posterior.set_default_x(torch.zeros(num_dim))
    
    # Tiny sample request triggers the bug
    num_samples = 10
    steps = 5
    samples = posterior.sample(sample_shape=(num_samples,), steps=steps)
    
    print('num_samples: ', num_samples)
    print('steps: ', steps)
    print("Requested samples:", num_samples)
    print("Returned samples shape:", samples.shape)

    I ran this with two parameter settings for num_samples, steps, (100, 10) and (10, 5). Here is the output I get

    (sbi) schmidt@node-63:~/gsoc2026/sbi$ python minimal_vp_uniform_repro.py 
    Generating 100 posterior samples in 9 diffusion steps.: 100%|████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 424.57it/s]
    100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:00<00:00, 4395.02it/s]
    num_samples:  100
    steps:  10
    Requested samples: 100
    Returned samples shape: torch.Size([100, 1])
    (sbi) schmidt@node-63:~/gsoc2026/sbi$ python minimal_vp_uniform_repro.py 
    Generating 10 posterior samples in 4 diffusion steps.: 100%|█████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 211.11it/s]
    Generating 100 posterior samples in 4 diffusion steps.: 100%|████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 116.32it/s]
    102it [00:00, 1841.48it/s]                                                                                                                                      
    num_samples:  10
    steps:  5
    Requested samples: 10
    Returned samples shape: torch.Size([10, 1])
    

    @vagechirkov do I understand you correctly, that the tqdm style iteration log should look differently?

    (sbi) schmidt@node-63:~/gsoc2026/sbi$ python --version && uv pip show sbi | grep Version
    Python 3.12.12
    Version: 0.25.0
    
  12. manuelgloeckler commented on Mar 3, 2026

    @manuelgloeckler
    Contributor

    Hey @Jocho-Smith ,

    I think your current reproducer is missing the iid setting i.e. it currently only works with a single observation but this issue is about auto_gauss_iid_8_iid_trial tests. For NPSE there happens quite a lot of thinks, in the IID case so this should be checked i.e. in your current example use:

    # x_iid is of shape e.g. (8, 1) in contrast to current (1,)
    posterior.sample(sample_shape=(1000,), x=x_iid, iid_method="auto_gauss")

    I am also not exactly sure, the incorrect number of posterior sample issue exits here i.e. Based on the limited traceback from @vagechirkov , I can see that the test did fail due to high C2ST (i.e. bad approximation). But this is totally expected due to step=5 (i.e. only 5 diffusion steps) yielding a bad approximation.

    I think what is confusing are the multiple progress bars with different number of samples. Specifically auto_gauss does one initial sampling run to estimate its hyperparameters here. It might makes sense to surpress the progress bar that might appears there.

  13. Jocho-Smith commented on Mar 12, 2026

    @Jocho-Smith
    Contributor

    Thanks for the clarification @manuelgloeckler !

    Here is how I adopted your suggestion in a test file:

    import torch
    import pytest
    from sbi.inference import NPSE
    from sbi.utils import BoxUniform
    from sbi.simulators import linear_gaussian
    
    @pytest.mark.slow
    def test_npse_auto_gauss_iid_uniform():
        """Test NPSE auto_gauss with IID inputs for uniform prior"""
        
        num_dim = 1
        num_simulations = 5
        num_samples = 10
        steps = 5
        num_trial = 8
    
        prior = BoxUniform(-2 * torch.ones(num_dim), 2 * torch.ones(num_dim))
        likelihood_shift = -1.0 * torch.ones(num_dim)
        likelihood_cov = 0.3 * torch.eye(num_dim)
    
        theta = prior.sample((num_simulations,))
        x = linear_gaussian(theta, likelihood_shift, likelihood_cov)
    
        inference = NPSE(prior, sde_type="vp", show_progress_bars=False)
        inference.append_simulations(theta, x).train(stop_after_epochs=3)
    
        posterior = inference.build_posterior()
        x_iid = torch.zeros(num_trial, num_dim) 
        samples = posterior.sample(
            sample_shape=(num_samples,),
            steps=steps,
            iid_method="auto_gauss",
            x=x_iid,  
            
        )
    
        expected_shape = (num_samples, num_dim)
        assert samples.shape == expected_shape, (
            f"Expected shape {expected_shape}, got {samples.shape}"
        )

    I ran this with pytest -s tests/test_npse_auto_gauss_iid.py, I can still confirm, that there is no shape miss match. I think the initial confusion was indeed only b/c of the status bar. If you still think this should be tested, I can add this test via a PR.


    Also I spent some time investigating the multiple progress bars that appear when using iid_method="auto_gauss" and tried to trace where they originate from.

    From debugging the call stack, the sampling pipeline looks roughly like this:

    • posterior.sample
      • accept_reject_sample (called irregardless of the value of reject_outside_prior)
        • _sample_via_diffusion (passed as input via proposal for accept_reject_sample)
          • Diffuser.run (here is the actual status bar)

    The diffusion sampler (Diffuser.run) is therefore used as the proposal distribution inside rejection sampling, meaning it can be called multiple times during a single posterior.sample call.

    In practice this leads to output like:

    Generating 10 posterior samples in 4 diffusion steps  
    Generating 100 posterior samples in 4 diffusion steps  
    66it [00:01, ...]
    

    These progress indicators correspond to different parts of the algorithm:

    • The "Generating ... posterior samples" bars come from Diffuser.run
    • The 66it [...] bar comes from something else. It is not the "Drawing {num_samples} samples for" bar inside accept_reject_sample. That is before Diffuser.run.

    To sum this up: I tried understanding it and I tried multiple runs where I just 'grid searched' different combinations of values for show_progress_bars (within different abstraction layers in the code) and I failed to make it happen. Either you see both bars or none of them.

    The only way I see to realize this is to additionally keep track of when/why Diffuser.run is called to differentiate between the different calls. I doubt though, that this is worth the hustle.

    Hope there is some value in what I did here :D

  14. manuelgloeckler commented on Mar 12, 2026

    @manuelgloeckler
    Contributor

    Thanks @Jocho-Smith for investigating this in detail! I agree with your evaluation and I do not think a test is required.

    I hence will close this issue here. For the progress bar problem I would create a new "enhancement" request for this pointing to your analysis here. I think one consideration would be to just remove Diffuser.run progressbar, by I will move this to the discussion to the new issue #1811.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

beginner friendlybughackathontests

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions