Skip to content

Add DensityEstimatorBuilder with build() dispatch - #1877

Merged
janfb merged 18 commits into
sbi-dev:gsoc-2026from
satwiksps:nn-builder-refactor-pr-two
Jun 19, 2026
Merged

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

Conversation

@satwiksps

Copy link
Copy Markdown
Collaborator

What does this PR do?

This is the second PR for for the Neural Network (NN) Builder API refactor project under GSoC 2026. It adds DensityEstimatorBuilder which is the first concrete builder class in the NN builder refactor. It provides a typed, inspectable replacement for the posterior_nn()/likelihood_nn() factory closures, covering all 14 continuous density estimator model types.

Builds on PR #1872 which introduced BuildContext, ZScoreConfig, ZScoreStats, and the _EstimatorBuilderBase contract.

Files Changed

sbi/neural_nets/net_builders/estimator_configs.py

  • Added DensityEstimatorBuilder(_EstimatorBuilderBase) dataclass with:
    • model: Literal[...] field selecting the architecture (maf, nsf, mdn, made, maf_rqs, and all Zuko variants)
    • Typed fields for all shared and model-specific parameters (hidden_features, num_transforms, num_bins, embedding_net, etc.)
    • __post_init__ validation: unknown model names fail immediately at construction
    • build(context, batch_theta, batch_x): dispatches to the appropriate existing build_* function
    • _build_kwargs(): collects non-None fields + extra_kwargs, excluding model (used only for dispatch)
  • Added DENSITY_MODELS type alias and _VALID_DENSITY_MODELS set for validation

sbi/neural_nets/net_builders/__init__.py

  • Exported DensityEstimatorBuilder

tests/density_estimator_builder_test.py (created new file, or may be we can also add to existing test files ?)

  • 43 tests covering construction, validation, to_dict, build dispatch for all 14 models, custom features, embedding nets, loss computation, and z-score options

AI Usage

  • GPT-OSS 120B (via Antigravity 2.0): Used to add docstrings and a few more tests.
  • Grammarly: Used to refine and improve the grammar of this PR description.
  • VS Code auto-complete: Used some suggested code and comments.
  • Gemini 3.1 Pro (via Antigravity 2.0): Used to scan for any bugs or architectural errors, code review prior push.

Does this close any issues?

N/A

Any relevant code examples, logs, or error messages?

N/A

@satwiksps

satwiksps commented Jun 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

This is a stacked PR, so opening as a Draft. Once the PR #1872 is merged into a new GSoC specific branch, I will rebase this branch and mark it Ready for review.

@satwiksps
satwiksps changed the base branch from main to gsoc-2026 June 9, 2026 13:00
@satwiksps
satwiksps force-pushed the nn-builder-refactor-pr-two branch from feb2d25 to 0737ed4 Compare June 15, 2026 12:33
@satwiksps
satwiksps marked this pull request as ready for review June 15, 2026 12:34
@codecov

codecov Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (gsoc-2026@d0afd1d). Learn more about missing BASE report.

Additional details and impacted files
@@             Coverage Diff              @@
##             gsoc-2026    #1877   +/-   ##
============================================
  Coverage             ?   87.97%           
============================================
  Files                ?      144           
  Lines                ?    13448           
  Branches             ?        0           
============================================
  Hits                 ?    11831           
  Misses               ?     1617           
  Partials             ?        0           
Flag Coverage Δ
fast 81.52% <100.00%> (?)

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

Files with missing lines Coverage Δ
sbi/neural_nets/net_builders/__init__.py 100.00% <100.00%> (ø)
sbi/neural_nets/net_builders/estimator_configs.py 100.00% <100.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.

Great follow-up @satwiksps 👍
I added a couple of minor comments, and a larger one regarding our general plan. I suggest to drop the context arg for now as we are still relying on the internal z-scoring and don't need the context at all for now.

this also implies that we should make the ZScoreConfig and ZScoreStats and compute_z_score_stats all private for now, to not make any promises in terms of public API. this will be added later.

for the follow-up #1882 , you would need to adapt a bit to the drop of context, let's discuss in our meeting.

great work! 👏

build_resnet_classifier,
)
from sbi.neural_nets.net_builders.estimator_configs import (
DensityEstimatorBuilder,

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.

cosmetics: please check whether removing the comma keeps it all in one line.

Comment on lines +223 to +238
_VALID_DENSITY_MODELS = {
"mdn",
"made",
"maf",
"maf_rqs",
"nsf",
"zuko_nice",
"zuko_maf",
"zuko_nsf",
"zuko_ncsf",
"zuko_sospf",
"zuko_naf",
"zuko_unaf",
"zuko_gf",
"zuko_bpf",
}

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 have this separate as a set, but we could still re-use the definition from above via frozenset(get_args(DENSITY_MODELS)) (needs to import get_args from typing).

# --- Shared across most builders ---
z_score_x: Optional[str] = None
z_score_y: Optional[str] = None
hidden_features: Optional[Any] = None

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 could be more strict, e.g, hidden_features = Optional[Union[int, Sequence[int]]] (because zuko allows sequence.

Comment on lines +254 to +255
z_score_x: Optional[str] = None
z_score_y: Optional[str] = None

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.

could make this literals as well, like in the build_* funs, e.g., Literal["none","independent","structured","transform_to_unconstrained"] or will this be too strict at this level? please check the pyright consequences.

Comment thread tests/density_estimator_builder_test.py Outdated
)


def test_density_estimator_builder_defaults():

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.

defaults are hard coded, we don't need to check for them again. can be dropped.

Comment thread tests/density_estimator_builder_test.py Outdated


@pytest.mark.parametrize("model", sorted(_VALID_DENSITY_MODELS))
def test_density_estimator_builder_accepts_valid_models(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.

mostly covered by test_density_estimator_builder_build except the dataclass default model, so also trivial I think. I suggest to drop, but please double check.

Comment thread tests/density_estimator_builder_test.py Resolved
Comment thread tests/density_estimator_builder_test.py Resolved
Comment thread tests/density_estimator_builder_test.py Resolved
@satwiksps

Copy link
Copy Markdown
Collaborator Author

I have worked upon the minor comments as per review. For the major change related to context I will work on it after our meeting today.

@satwiksps
satwiksps requested a review from janfb June 17, 2026 17:01

@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 very good @satwiksps 👍 all my previous comments perfectly addressed. I just found some typing constraints that we should add, that's the last thing before we can merge 🚀


def build(self, context: BuildContext) -> Any:
"""Build an estimator from a ``BuildContext``.
def build(self, batch_theta: Tensor, batch_x: Tensor) -> Any:

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 return type could be more specialized, e.g., ConditionalEstimator?
needs an import from sbi.neural_nets.estimators.base

f"Must be one of {sorted(_VALID_DENSITY_MODELS)}."
)

def build(self, batch_theta: Tensor, batch_x: Tensor):

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 return specialized for this subclass method, e.g., ConditionalDensityEstimator. needs an import from from sbi.neural_nets.estimators.base as well.

same for all future specific builders. It's ok to have subclass return types different from the parent class because the type has been defined with covariant=True.

@satwiksps
satwiksps requested a review from janfb June 18, 2026 18:59

@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 @satwiksps 🚀

@janfb
janfb merged commit cfe8422 into sbi-dev:gsoc-2026 Jun 19, 2026
9 checks passed
@janfb
janfb deleted the nn-builder-refactor-pr-two branch June 19, 2026 10:33
@janfb
janfb restored the nn-builder-refactor-pr-two branch June 19, 2026 10:33
Jocho-Smith pushed a commit to Jocho-Smith/sbi that referenced this pull request Jul 20, 2026
…1877)

* export DensityEstimatorBuilder from net_builders

* add supported density model definitions

* add the DensityEstimatorBuilder class

* add tests

* add proper docstrings to estimator_configs new class

* add some more tests for DensityEstimatorBuilder

* cosmetic change to keep import in one line

* re-use DENSITY_MODELS definition

* make literals strict

* drop trivial tests

* add necessary asserts to tests

* fix comment line too long error

* remove BuildContext from base class

* remove context from tests

* update builder base test

* more specialized return type

* Apply suggestion from @janfb

Co-authored-by: Jan Teusen (né Boelts) <[email protected]>

* wrap docstring to fix E501 Line too long

---------

Co-authored-by: Jan Teusen (né Boelts) <[email protected]>
janfb pushed a commit that referenced this pull request Aug 5, 2026
Ports #1877, which was reviewed and merged into the `gsoc-2026`
branch. See that pull request for the full description.

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

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