Skip to content

Integrate DensityEstimatorBuilder into NLE - #1904

Merged
janfb merged 10 commits into
sbi-dev:gsoc-2026from
satwiksps:nn-builder-refactor-pr-three-point-five
Jul 1, 2026
Merged

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

Conversation

@satwiksps

Copy link
Copy Markdown
Collaborator

What does this PR do?

This PR continues the Neural Network (NN) Builder API refactor project under GSoC 2026. It does two things:

  1. Refactors build() to a role neutral signature : the _EstimatorBuilderBase.build() and DensityEstimatorBuilder.build() methods now take (batch_input, batch_condition) instead of the NPE-specific (batch_theta, batch_x).
  2. Integrates DensityEstimatorBuilder into the NLE trainer : similar to what PR Integrate DensityEstimatorBuilder into NPE trainers #1882 did for NPE, this wires builder support into LikelihoodEstimatorTrainer and NLE_A. Users can now pass a builder object as the density_estimator argument instead of a string or callable.

Files Changed

estimator_configs.py:

  • Renamed build() params from (batch_theta, batch_x) to (batch_input, batch_condition) on both _EstimatorBuilderBase and DensityEstimatorBuilder and then updated docstrings.

npe_base.py:

  • Updated the closure to explicitly assign NPE roles: build(batch_input=batch_theta, batch_condition=batch_x)

nle_base.py:

  • Added DensityEstimatorBuilder and _EstimatorBuilderBase imports and changed density_estimator default from "maf" to None
  • Added _wrap_builder with NLE role assignment: build(batch_input=batch_x, batch_condition=batch_theta) the opposite of NPE, since NLE models p(x|θ) not p(θ|x)

nle_a.py:

  • Updated density_estimator type union and default to match the base class
  • Updated docstring to describe all four input types

npe_nle_builder_integration_test.py

  • Renamed from npe_builder_integration_test.py and added tests for likelihood estimation in same file

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): Some smoke tests to scan for any errors and verify before final push.

Does this close any issues?

N/A

Any relevant code examples, logs, or error messages?

N/A

@satwiksps satwiksps changed the title Nn builder refactor pr three point five Integrate DensityEstimatorBuilder into NLE Jun 29, 2026
@satwiksps
satwiksps marked this pull request as ready for review June 29, 2026 14:03
@codecov

codecov Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 1 line in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (gsoc-2026@9005530). Learn more about missing BASE report.

Files with missing lines Patch % Lines
sbi/inference/trainers/nle/mnle.py 75.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             gsoc-2026    #1904   +/-   ##
============================================
  Coverage             ?   87.99%           
============================================
  Files                ?      144           
  Lines                ?    13499           
  Branches             ?        0           
============================================
  Hits                 ?    11879           
  Misses               ?     1620           
  Partials             ?        0           
Flag Coverage Δ
fast 81.57% <95.65%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/trainers/nle/nle_a.py 100.00% <100.00%> (ø)
sbi/inference/trainers/nle/nle_base.py 97.36% <100.00%> (ø)
sbi/inference/trainers/npe/npe_base.py 93.38% <100.00%> (ø)
sbi/neural_nets/net_builders/estimator_configs.py 100.00% <100.00%> (ø)
sbi/inference/trainers/nle/mnle.py 92.59% <75.00%> (ø)

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

Clean PR @satwiksps 👏 The one thing to fix is a side effect on MNLE: because you (correctly) added the string deprecation to the shared NLE base, MNLE's default "mnle" now raises it with wrong advice. MNPE already sidesteps this by converting its string to a callable before calling super(). You can just mirror that one line in MNLE and add a no-warning test. On the tests we can reduce the code duplication between NPE and NLE integration tests by using parametrize, see comments below.

Comment thread sbi/inference/trainers/nle/nle_base.py Resolved

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.

good to unify the NPE and NLE tests into one file. We can go even one step further and use parametrize on the NLE and NPE objects on single tests that are currently duplicated as nearly twin-tests for NPE and NLE in this file. This should work because we now have a unified API.

e.g., sth like:

TRAINERS = [(NPE_C, posterior_nn, "theta"), (NLE_A, likelihood_nn, "x")]  # input_is

@pytest.mark.parametrize("trainer,factory", [(t, f) for t, f, _ in TRAINERS], ids=["npe", "nle"])
  def test_string_emits_deprecation_warning(trainer, factory):
      prior = MultivariateNormal(zeros(2), eye(2))
      with pytest.warns(FutureWarning, match="deprecated"):
          trainer(prior, density_estimator="maf", show_progress_bars=False)

And similar for many of the other tests in this file.

We can even extend this to MNPE and MNLE later when they are introduced as well. What do you think?

You could do this for all twin tests. But try to find a balance with saving test code and adding test complexity. If it's hard or just adds a lot of complexity to find a general way to write the test, keep the twin tests.

Comment thread sbi/inference/trainers/nle/nle_a.py Outdated
`.sample()` and must return a `ConditionalDensityEstimator`.
density_estimator: If it is a string (deprecated), use a pre-configured
network of the provided type (one of nsf, maf, mdn, made). If it is
a `DensityEstimatorBuilder``, the builder's `build()` method will be

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.

typo ``

The naming follows the internal convention of ``posterior_nn``: the
caller passes ``batch_theta`` as the modeled variable and ``batch_x``
as the conditioning variable.

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.

double blank line.

signature as the functions produced by `likelihood_nn`.
"""

def build_fn(batch_theta, batch_x):

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.

add a small comment here: # NLE models p(x|θ): input=x, condition=θ

@satwiksps
satwiksps requested a review from janfb July 1, 2026 07:41

@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 good, thanks @satwiksps :shipit:

assert estimator.condition_shape == torch.Size([num_dim_theta])


@pytest.mark.parametrize("trainer_cls", [MNLE, MNPE], ids=["mnle", "mnpe"])

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.

👍

@janfb
janfb merged commit 587f922 into sbi-dev:gsoc-2026 Jul 1, 2026
9 checks passed
Jocho-Smith pushed a commit to Jocho-Smith/sbi that referenced this pull request Jul 20, 2026
* change build to neutral batch_input and batch_condition signature

* update NPE wrap builder for role neutral build

* wire DensityEstimatorBuilder into LikelihoodEstimatorTrainer

* update NLE_A type hints and docstring fro builder support

* rename and extend tests for NPE and NLE builder integration

* update old batch_x batch_theta call in pr2 test file

* fix typo and double blank line

* convert MNLE string to callable before super to avoid spurious warning

* parametrize twin tests and add MNLE MNPE no warning regression

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

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

(cherry picked from commit 587f922)
@satwiksps
satwiksps deleted the nn-builder-refactor-pr-three-point-five 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