Skip to content

Integrate DensityEstimatorBuilder into NPE trainers - #1882

Merged
janfb merged 20 commits into
sbi-dev:gsoc-2026from
satwiksps:nn-builder-refactor-pr-three
Jun 24, 2026
Merged

janfb merged 20 commits into
sbi-dev:gsoc-2026from
satwiksps:nn-builder-refactor-pr-three

Conversation

@satwiksps

Copy link
Copy Markdown
Collaborator

What does this PR do?

This is the third PR for for the Neural Network (NN) Builder API refactor project under GSoC 2026. It integrates the DensityEstimatorBuilder (introduced in PR #1877) into the NPE trainer hierarchy. Users can now pass a builder object to PosteriorEstimatorTrainer, NPE_B, NPE_C, and MNPE as the density_estimator argument instead of a string or callable.

Files Changed

Core integration (npe_base.py)

  • Extended density_estimator type union to include _EstimatorBuilderBase
  • Added _wrap_builder() static method that adapts a builder object to the existing _build_neural_net(theta, x) callable interface, keeping _initialize_neural_network unchanged
  • Emit FutureWarning when a string is passed to density_estimator (deprecation path)

Type annotation updates

  • npe_b.py, npe_c.py, mnpe.py: Updated density_estimator parameter type annotations and docstrings to include _EstimatorBuilderBase

Validation (user_input_checks.py)

  • Extended check_estimator_arg to accept _EstimatorBuilderBase instances alongside strings and callables

Tests (npe_builder_integration_test.py) this is a new file again

  • test_npe_accepts_builder: parametrized over 4 models
  • test_npe_string_emits_deprecation_warning
  • test_npe_callable_no_warning
  • test_npe_train_with_builder: parametrized over 3 models, trains for 2 epochs
  • test_npe_build_posterior_with_builder: end-to-end: builder, then train, then sample
  • test_check_estimator_arg_accepts_valid_inputs: parametrized (builder/str/callable)
  • test_check_estimator_arg_rejects_module

Backward compatibility

  • The string path density_estimator="maf" still works but now emits a FutureWarning. No behavior change.
  • The callable path (posterior_nn(...) or custom function works without any warning.

AI Usage

  • Grammarly: Used to refine and improve the grammar of this PR description.
  • VS Code auto-complete and co-pilot chatbot: Used some suggested code, comments and bug fix suggestions.
  • Claude Opus 4.6 (via Antigravity 2.0): It did some smoke tests to scan for any errors, all okay though.

Does this close any issues?

N/A

Any relevant code examples, logs, or error messages?

N/A

@satwiksps
satwiksps force-pushed the nn-builder-refactor-pr-three branch from 3a6ffc5 to 914091c Compare June 22, 2026 06:28
@satwiksps
satwiksps marked this pull request as ready for review June 22, 2026 07:44
@codecov

codecov Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.30769% with 2 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (gsoc-2026@cfe8422). Learn more about missing BASE report.

Files with missing lines Patch % Lines
sbi/inference/trainers/npe/mnpe.py 71.42% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             gsoc-2026    #1882   +/-   ##
============================================
  Coverage             ?   87.98%           
============================================
  Files                ?      144           
  Lines                ?    13470           
  Branches             ?        0           
============================================
  Hits                 ?    11851           
  Misses               ?     1619           
  Partials             ?        0           
Flag Coverage Δ
fast 81.52% <92.30%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/trainers/npe/npe_b.py 100.00% <100.00%> (ø)
sbi/inference/trainers/npe/npe_base.py 93.38% <100.00%> (ø)
sbi/inference/trainers/npe/npe_c.py 93.78% <100.00%> (ø)
sbi/utils/user_input_checks.py 76.92% <100.00%> (ø)
sbi/inference/trainers/npe/mnpe.py 90.00% <71.42%> (ø)

@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.

Really good progress and the first internal integration of the new API @satwiksps 🎉

I have some typing suggestions and we need to handle MNPE a bit differently. Tests can be a bit leaner again, made some comments. But looks very good overall! 🙌

Comment thread sbi/inference/trainers/npe/npe_b.py Resolved
Comment thread sbi/inference/trainers/npe/npe_b.py Resolved
Comment thread sbi/inference/trainers/npe/npe_base.py Resolved
Comment thread sbi/inference/trainers/npe/npe_base.py Resolved
Comment thread sbi/inference/trainers/npe/npe_base.py Outdated
Literal["nsf", "maf", "mdn", "made"],
_EstimatorBuilderBase,
ConditionalEstimatorBuildFn[ConditionalDensityEstimator],
] = "maf",

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.

when we leave this as string ="maf", the warning below will fire all the time becuase it's the default.

I suggest we set this to None here (and in all suclasses) and then set the default below in the if-else.

Comment thread tests/npe_builder_integration_test.py Outdated
NPE_C(prior, density_estimator="maf", show_progress_bars=False)


def test_npe_callable_no_warning():

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.

this one could be extended to cover both, the default (NPE_C()) and the build_fn approach.

Comment thread tests/npe_builder_integration_test.py Outdated
build_fn = posterior_nn(model="maf")
# Should not warn.
inference = NPE_C(prior, density_estimator=build_fn, show_progress_bars=False)
assert inference._build_neural_net is build_fn

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.

the test promises to test for no warning, but then does not check it. you can do so using a filter:

import warnings
with warnings.catch_warnings():
    warnings.simplefilter("error", FutureWarning)   # turn any FutureWarning into a failure
    inference = NPE_C(prior, density_estimator=builder, show_progress_bars=False)

Comment thread tests/npe_builder_integration_test.py Outdated


@pytest.mark.parametrize("model", ("maf", "nsf"))
def test_npe_build_posterior_with_builder(model):

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.

this test can be combined with the one above, just construct the posterior as well and draw samples, that way we train only once.

Comment thread tests/npe_builder_integration_test.py Outdated

def test_check_estimator_arg_rejects_module():
"""check_estimator_arg should reject raw nn.Module instances."""
with pytest.raises(AssertionError):

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.

should be a TypeError is you implement the above comment. please change.

Comment thread tests/npe_builder_integration_test.py Resolved
@satwiksps
satwiksps requested a review from janfb June 24, 2026 07:21

@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.

All good! Thanks for the quick fixes 💯 @satwiksps

@janfb
janfb merged commit bd677a1 into sbi-dev:gsoc-2026 Jun 24, 2026
9 checks passed
Jocho-Smith pushed a commit to Jocho-Smith/sbi that referenced this pull request Jul 20, 2026
…v#1882)

* accept DensityEstimatorBuilder in PosteriorEstimatorTrainer

* add warning

* update NPE_C type annotation for builder support

* update NPE_B type annotation for builder support

* update MNPE type annotation for builder support

* add input validation and deprecation tests

* add integration tests for training and sampling with estimator builders

* remove BuildContext from npe_b and npe_c docstrings

* BuildContext related changes in npe_base

* allow _EstimatorBuilderBase in check_estimator_arg

* minor import cleanup in npe_base.py

* trigger ci

* add an explicit loss check

* default density estimator to None and update type hints in npe base

* update density estimator type hints and default in npe b and c

* raise Type error instead of Assertion error in check_estimator_arg

* not implemented error in mnpe

* assertion error to type error and adjust in one line

* merge test

* final cleanup for tests
janfb pushed a commit that referenced this pull request Aug 5, 2026
Ports #1882, which was reviewed and merged into the `gsoc-2026`
branch. See that pull request for the full description.

(cherry picked from commit bd677a1)
janfb pushed a commit that referenced this pull request Aug 5, 2026
Ports #1882, which was reviewed and merged into the `gsoc-2026`
branch. See that pull request for the full description.

(cherry picked from commit bd677a1)
@satwiksps
satwiksps deleted the nn-builder-refactor-pr-three branch August 7, 2026 10:48
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