Skip to content

Adding interface for unconditional flow training - #1470

Merged
janfb merged 7 commits into
sbi-dev:mainfrom
plcrodrigues:issue_1432_unconditional_density
Mar 21, 2025
Merged

janfb merged 7 commits into
sbi-dev:mainfrom
plcrodrigues:issue_1432_unconditional_density

Conversation

@plcrodrigues

Copy link
Copy Markdown
Collaborator

This PR implements the proposal from issue #1432 and is part of a larger goal of including tools for testing and evaluating model misspecification in sbi. I thought it was easier to consider only density estimators coming from zuko and have only tested what happens when they are discrete normalizing flows (e.g. MAF, NSF) for now. I'm not sure of how urgent it is to add the possibility of doing flow matching or score diffusion for unconditional pdfs.

In any case, the following code tests the implementation :

from torch.distributions import (
    Normal,
    MultivariateNormal,
    Exponential,
    Uniform,
    Categorical,
    MixtureSameFamily
)
import torch
from sbi.inference.trainers.marginal import MarginalEstimator
from sbibm.metrics import c2st

n_samples = 5_000

dist_dict = {}

mu = torch.tensor([2.0, 3.0])
cv = torch.tensor([[1.0, 0.0], [0.0, 4.0]])
dist_dict['multivariate_normal'] = MultivariateNormal(loc=mu,
                                                      covariance_matrix=cv)

rate = torch.tensor([2.0])
dist_dict['exponential'] = Exponential(rate=rate)

a, b = torch.tensor([-1.0]), torch.tensor([2.0])
dist_dict['uniform'] = Uniform(a, b)

n_components = 2
mix = Categorical(torch.ones(n_components,))
comp = Normal(torch.randn(n_components,), torch.rand(n_components,))
dist_dict['mixture'] = MixtureSameFamily(mix, comp)

est_dict = {}

for key in dist_dict.keys():

    print(f'Running {key} example...')

    x = dist_dict[key].sample((n_samples,))
    if len(x.shape) == 1:
        x = x.unsqueeze(1)
    est = MarginalEstimator(density_estimator='NSF')
    est.append_simulations(x)
    est.train(max_num_epochs=3000)
    s = est.sample((n_samples,))
    score = c2st(x, s)

    est_dict[key] = est

    print('')
    print(f'C2ST: {score.item():.2f}')
    print('')

The output that we get is :

Running multivariate_normal example...
 Training neural network. Epochs trained: 23
C2ST: 0.50

Running exponential example...
 Training neural network. Epochs trained: 118
C2ST: 0.50

Running uniform example...
 Training neural network. Epochs trained: 221
C2ST: 0.51

Running mixture example...
 Training neural network. Epochs trained: 153
C2ST: 0.50

Any comments, suggestions, reviews are welcome :-)

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left some comments but I think it makes sense / is more efficient to discuss this in person. how about later today, 4pm?

Comment thread sbi/inference/trainers/base.py Resolved
Comment thread sbi/neural_nets/estimators/base.py Resolved
@codecov

codecov Bot commented Mar 18, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 84.61538% with 34 lines in your changes missing coverage. Please review.

Project coverage is 79.14%. Comparing base (a1d7555) to head (ac79737).
Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
sbi/neural_nets/estimators/base.py 54.83% 14 Missing ⚠️
sbi/neural_nets/estimators/zuko_flow.py 66.66% 9 Missing ⚠️
sbi/neural_nets/net_builders/flow.py 73.91% 6 Missing ⚠️
sbi/inference/trainers/marginal/marginal_base.py 96.92% 4 Missing ⚠️
sbi/neural_nets/__init__.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main    #1470       +/-   ##
===========================================
- Coverage   89.60%   79.14%   -10.46%     
===========================================
  Files         121      123        +2     
  Lines        9357     9572      +215     
===========================================
- Hits         8384     7576      -808     
- Misses        973     1996     +1023     
Flag Coverage Δ
unittests 79.14% <84.61%> (-10.46%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
sbi/inference/trainers/base.py 92.54% <ø> (ø)
sbi/inference/trainers/marginal/__init__.py 100.00% <100.00%> (ø)
sbi/neural_nets/estimators/__init__.py 100.00% <100.00%> (ø)
sbi/neural_nets/factory.py 91.66% <100.00%> (+0.75%) ⬆️
sbi/neural_nets/__init__.py 58.82% <50.00%> (+45.49%) ⬆️
sbi/inference/trainers/marginal/marginal_base.py 96.92% <96.92%> (ø)
sbi/neural_nets/net_builders/flow.py 90.99% <73.91%> (-2.13%) ⬇️
sbi/neural_nets/estimators/zuko_flow.py 63.76% <66.66%> (-0.68%) ⬇️
sbi/neural_nets/estimators/base.py 61.11% <54.83%> (-3.30%) ⬇️

... and 37 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@plcrodrigues

Copy link
Copy Markdown
Collaborator Author

OK, now following @janfb suggestion for reorganization, we can have a script for testing the marginal pdf estimation as per:

from torch.distributions import (
    Normal,
    MultivariateNormal,
    Exponential,
    Uniform,
    Categorical,
    MixtureSameFamily
)
import torch
from sbi.inference.trainers.marginal import MarginalTrainer
from sbibm.metrics import c2st

n_samples = 5_000

dist_dict = {}

# Multivariate normal distribution
mu = torch.tensor([2.0, 3.0])
cv = torch.tensor([[1.0, 0.0], [0.0, 4.0]])
dist_dict['multivariate_normal'] = MultivariateNormal(loc=mu,
                                                      covariance_matrix=cv)

# Exponential distribution
rate = torch.tensor([2.0])
dist_dict['exponential'] = Exponential(rate=rate)

# Uniform distribution
a, b = torch.tensor([-1.0]), torch.tensor([2.0])
dist_dict['uniform'] = Uniform(a, b)

# Mixture of two univariate normal distributions
n_components = 2
mix = Categorical(torch.ones(n_components,))
comp = Normal(torch.randn(n_components,), torch.rand(n_components,))
dist_dict['mixture'] = MixtureSameFamily(mix, comp)

est_dict = {}

for key in dist_dict.keys():

    print(f'Running {key} example...')

    # Generate samples from the true distribution
    x = dist_dict[key].sample((n_samples,))
    if len(x.shape) == 1:
        x = x.unsqueeze(1)

    # Instantiate a trainer for the marginal pdf and train it
    trainer = MarginalTrainer(density_estimator='NSF')
    trainer.append_simulations(x)
    est = trainer.train(max_num_epochs=3000)

    # Sample from the marginal pdf estimator
    s = est.sample((n_samples,))

    # Compute the C2ST score
    score = c2st(x, s)

    est_dict[key] = est

    print('')
    print(f'C2ST: {score.item():.2f}')
    print('')

@janfb

janfb commented Mar 19, 2025

Copy link
Copy Markdown
Contributor

cool @plcrodrigues I tested this locally and it works like a charm.

my suggestions:

  • transform this into a test, e.g., 1-2 test cases would be enough (having a multimodal would be nice)
  • make sure test c2st on an unseen bag of samples
  • use from sbi.utils.metrics import c2st instead the sbibm one
  • rename append_simulations to append_samples

(see also comments in PR review).

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great stuff! added a couple of comments.

Comment thread sbi/neural_nets/estimators/base.py Resolved
Comment thread sbi/neural_nets/estimators/base.py Resolved

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great now, thanks a lot for adding this @plcrodrigues 🙏

We now can perform unconditional flow training for learning priors or p(x)! 🎉

@janfb
janfb merged commit c075a99 into sbi-dev:main Mar 21, 2025
dgedon added a commit that referenced this pull request Nov 23, 2026
…d and unconditional estimator defaults (#2158)

* fix(estimators): keep nflows sample_and_log_prob samples with their condition

nflows returns samples and log probs as (batch, sample). `sample_and_log_prob`
reshaped them without the transpose that `sample()` got in #1155, so with
several conditions it filed half of the samples and their log probs under the
wrong condition. The #1155 test now also checks `sample_and_log_prob` against
`log_prob`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(estimators): use self.net in the unconditional density estimator base

`UnconditionalDensityEstimator.log_prob` and `sample` used `self._neural_net`,
which is never set, so subclasses that keep these methods raised an
AttributeError. They now use `self.net` and keep the `eval()` call from #1470.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(samplers): thin serial slice_np chains once

`SliceSamplerSerial.run(n)` built each chain's `SliceSampler` with `thin`, which
already takes `thin` steps per kept sample, and then thinned the result again.
With `thin > 1` this cost `thin` times more potential evaluations and kept every
`thin**2`-th step. The chain sampler now uses `thin=1`, so `run(n)` takes `n`
steps and thins once, as `SliceSamplerVectorized` does. Seeded `slice_np`
results with `thin > 1` change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(posteriors): make mcmc_method and set_mcmc_method set the sampling method

`MCMCPosterior.mcmc_method` read `self._mcmc_method`, which `__init__` never
sets, and `set_mcmc_method` wrote that attribute while sampling reads
`self.method`. So the getter raised, and after setting a method the posterior
reported it but kept sampling with the old one. Both now use `self.method`, and
`set_mcmc_method` raises for unknown methods, as `__init__` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(estimators): leave train/eval mode to the caller in unconditional log_prob

`UnconditionalDensityEstimator.log_prob` called `self.net.eval()`, so a subclass
whose `loss` uses `log_prob` was trained with Dropout and BatchNorm in eval mode.
The trainer sets the mode, as for the other estimators.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor: type set_mcmc_method as MCMCPosterior, reshape as in sample()

`set_mcmc_method` returns the posterior itself, so its signature and docstring
now say `MCMCPosterior` and type checkers follow chained calls.
`NFlowsFlow.sample_and_log_prob` reshapes samples to `self.input_shape`, as
`sample()` does; the shapes are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants