Skip to content

port: NN-builder series (PR1-5) from gsoc-2026 to main - #1957

Merged
janfb merged 10 commits into
mainfrom
satwik-builders-to-main
Aug 5, 2026
Merged

janfb merged 10 commits into
mainfrom
satwik-builders-to-main

Conversation

@janfb

@janfb janfb commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Ports the merged NN-builder refactor series from gsoc-2026 to main: #1872, #1877, #1882, #1904, #1912, #1920. The six commits keep Satwik's authorship and each body points at the original pull request for its description.

On top of those, four review fixes:

  • 51216e65 fix: align low-level build defaults with the factory defaults. The builders dispatch straight to the build_* functions, so a differing default silently changed the network the trainers build — MNLE()/MNPE() had lost capacity this way.
  • 521dbfcf fix: correct how the trainers handle the density_estimator argument. A builder of the wrong family fell through to the generic callable branch and failed later with an unrelated error; each trainer now declares what it accepts in _ALLOWED_BUILDER_TYPES. NPE_A(prior) also warned about a deprecated string the user never passed.
  • 11acc7d9 feat: expose transform_to_unconstrained and x_dist on the density builders. Input side only — the condition side never applies the transform, so offering it there would silently do nothing.
  • 2031a40b fix: correct the builder argument surface. The NRE builder exposed the build functions' positional x/y naming, in which embedding_net_x applies to theta, so a user following classifier_nn embedded the parameters with the net meant for the data. And extra_kwargs, as the first base-class field, was every builder's first positional parameter, so DensityEstimatorBuilder("nsf") bound the model name to extra_kwargs and silently built the default MAF.

Merge with rebase-merge, not squash, to keep per-commit attribution.

  • v0.27.0 tagged (this API ships with 0.28)
  • Review from @satwiksps
  • CI green on 2031a40b
  • Rebase-merge
  • Changelog entry when this ships with 0.28, including the changed build-fn defaults

CodeRabbit review: findings fixed here are the keyword-only extra_kwargs and two stale docstrings. Its mixed-builder validation finding is declined — _build_mixed_density_estimator does forward num_transforms to build_mdn, but build_mdn drops it, so the rejection is correct and the proposed union-of-signatures fix would restore the silent-ignore behaviour the check exists to prevent.

@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.81657% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.96%. Comparing base (48dcd35) to head (2031a40).
⚠️ Report is 31 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/utils/user_input_checks.py 71.42% 2 Missing ⚠️
sbi/neural_nets/build_context.py 97.56% 1 Missing ⚠️
sbi/neural_nets/net_builders/estimator_configs.py 99.43% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1957      +/-   ##
==========================================
- Coverage   88.02%   87.96%   -0.06%     
==========================================
  Files         143      144       +1     
  Lines       13558    17348    +3790     
==========================================
+ Hits        11934    15260    +3326     
- Misses       1624     2088     +464     
Flag Coverage Δ
fast 83.82% <98.81%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/trainers/nle/mnle.py 97.14% <100.00%> (+1.30%) ⬆️
sbi/inference/trainers/nle/nle_a.py 100.00% <100.00%> (ø)
sbi/inference/trainers/nle/nle_base.py 97.50% <100.00%> (+0.62%) ⬆️
sbi/inference/trainers/npe/mnpe.py 97.14% <100.00%> (+1.30%) ⬆️
sbi/inference/trainers/npe/npe_a.py 59.46% <100.00%> (-19.52%) ⬇️
sbi/inference/trainers/npe/npe_b.py 100.00% <100.00%> (ø)
sbi/inference/trainers/npe/npe_base.py 94.47% <100.00%> (+1.72%) ⬆️
sbi/inference/trainers/npe/npe_c.py 93.72% <100.00%> (+0.51%) ⬆️
sbi/inference/trainers/npe/npe_pfn.py 85.05% <ø> (ø)
sbi/inference/trainers/nre/bnre.py 97.29% <100.00%> (+0.07%) ⬆️
... and 16 more

... and 39 files with indirect coverage changes

@janfb
janfb marked this pull request as draft July 30, 2026 04:50
@janfb
janfb marked this pull request as ready for review August 4, 2026 14:09
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR adds immutable estimator builders and build-context types, updates NPE, NLE, and NRE trainers to use them, renames the estimator build protocol, deprecates string configuration, exports builder classes, adjusts network defaults, and adds unit and integration tests.

Changes

Estimator builder API migration

Layer / File(s) Summary
Build context, protocol, and shared builder foundation
sbi/neural_nets/build_context.py, sbi/neural_nets/estimators/base.py, sbi/neural_nets/net_builders/estimator_configs.py, sbi/neural_nets/net_builders/vector_field_nets.py
Adds immutable build-context types, renames ConditionalEstimatorBuilder to ConditionalEstimatorBuildFn, and adds shared builder validation and serialization behavior.
Estimator builder dispatch and validation
sbi/neural_nets/net_builders/estimator_configs.py
Adds density, mixed-density, and ratio builders with model dispatch, field validation, alias translation, and estimator construction.
Neural network default configuration
sbi/neural_nets/net_builders/flow.py, sbi/neural_nets/net_builders/mixed_nets.py
Updates Zuko and mixed-density model defaults for bins, transforms, and mixture components.
Public exports and argument validation
sbi/neural_nets/__init__.py, sbi/neural_nets/net_builders/__init__.py, sbi/utils/user_input_checks.py
Exports builder classes and updates estimator argument validation to accept builders and callables.
NLE builder integration
sbi/inference/trainers/nle/*
NLE trainers accept builders, callables, and None defaults. Deprecated strings use legacy factories, and builders are adapted for existing initialization.
NPE builder integration
sbi/inference/trainers/npe/*
NPE trainers accept builders, callables, and None defaults. Deprecated strings remain supported, and NPE_A resolves its preset through posterior_nn.
NRE builder integration
sbi/inference/trainers/nre/*
NRE trainers accept ratio builders, callables, and None defaults. Deprecated strings are validated, and builders are adapted for initialization.
Vector-field updates
sbi/inference/trainers/vfpe/*, sbi/neural_nets/net_builders/vector_field_nets.py
Updates vector-field annotations and configuration inheritance to use the renamed protocol and shared builder base.
Builder and trainer integration tests
tests/*builder*, tests/build_context_test.py
Tests cover context inference, builder dispatch, field validation, warnings, training workflows, aliases, embedding routing, and incompatible inputs.

Estimated code review effort: 5 (Critical) | ~120 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 81.36% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed The description links the ported commits to pull requests and identifies related adjacent changes.
Out of Scope Changes check ✅ Passed The changes and tests align with the stated NN-builder refactor and its documented fixes.
Title check ✅ Passed The title clearly summarizes the main change: porting the NN-builder series from gsoc-2026 to main.
Description check ✅ Passed The description directly explains the refactor port, review fixes, validation, merge requirements, and release impact.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch satwik-builders-to-main

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
tests/density_estimator_builder_test.py (1)

71-81: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that the supplied embedding module is installed.

Line 81 only rejects nn.Identity. It does not prove that DensityEstimatorBuilder forwards emb into the estimator. Assert that an estimator submodule is the same object as emb.

Proposed test change
-    # The embedding net must not be a plain Identity.
-    assert not isinstance(estimator.embedding_net, nn.Identity)
+    assert any(module is emb for module in estimator.modules())
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/density_estimator_builder_test.py` around lines 71 - 81, Update
test_density_estimator_builder_build_with_embedding_net to assert that the built
estimator’s embedding_net is the exact emb object supplied to
DensityEstimatorBuilder, replacing the weaker nn.Identity check while preserving
the existing type assertion.
sbi/neural_nets/net_builders/flow.py (1)

586-586: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update stale num_bins docstring after the default change.

build_zuko_nsf and build_zuko_ncsf change the num_bins default from 8 to 10 (Line 586, Line 651). The docstrings for both functions still state "Defaults to 8" (Line 619, Line 679). Update the docstring text to match the new default value.

As per coding guidelines, **/*.py files must "Use Google-style docstrings for functions and classes", which requires the documented defaults to stay accurate.

📝 Proposed docstring fix
-        num_bins: The number of bins in the spline transformations. Defaults to 8.
+        num_bins: The number of bins in the spline transformations. Defaults to 10.

Apply this change at both Line 619 (build_zuko_nsf) and Line 679 (build_zuko_ncsf).

Also applies to: 619-619, 651-651, 679-679

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sbi/neural_nets/net_builders/flow.py` at line 586, Update the Google-style
docstrings for build_zuko_nsf and build_zuko_ncsf so their num_bins parameter
descriptions state a default of 10 instead of 8, matching the current function
signatures.

Source: Coding guidelines

sbi/neural_nets/net_builders/estimator_configs.py (2)

57-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Resolve field annotations before Literal validation.

If this module adds from __future__ import annotations, Field.type becomes a string and _literal_values() stops validating Literal fields. Cache get_type_hints(type(self)) once per builder class and pass the resolved annotations to _literal_values(). The explicit _VALID_* discriminator checks do not depend on Field.type.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sbi/neural_nets/net_builders/estimator_configs.py` around lines 57 - 85,
Update _EstimatorBuilderBase.__post_init__ to resolve annotations with
get_type_hints(type(self)) once per builder class, then pass each resolved field
annotation to _literal_values() instead of f.type. Preserve the existing
validation behavior and leave explicit _VALID_* discriminator checks independent
of Field.type.

70-76: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Mark extra_kwargs as keyword-only to prevent positional argument misuse.

extra_kwargs is the first field on _EstimatorBuilderBase, making it the first positional parameter of all builder subclasses. A user calling DensityEstimatorBuilder("nsf") assigns "nsf" to extra_kwargs instead of model. The model field retains its default value "maf", which is valid, so __post_init__() validation does not detect the error. All current tests use keyword arguments, which masks this hazard.

Add kw_only=True to prevent the base field from capturing positional arguments intended for subclass discriminators.

-    extra_kwargs: dict = field(default_factory=dict)
+    extra_kwargs: dict = field(default_factory=dict, kw_only=True)

The project requires Python 3.10 or newer (requires-python = ">=3.10" in pyproject.toml), so kw_only is available.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sbi/neural_nets/net_builders/estimator_configs.py` around lines 70 - 76,
Update the extra_kwargs field in _EstimatorBuilderBase to be keyword-only by
enabling the dataclass field’s kw_only option, ensuring positional arguments in
estimator builder subclasses bind to fields such as model instead of
extra_kwargs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@sbi/neural_nets/net_builders/estimator_configs.py`:
- Around line 397-414: Move the public type aliases DENSITY_MODELS and
CLASSIFIER_MODELS from estimator_configs.py to sbi/sbi_types.py to follow the
coding guideline that shared public type aliases belong in sbi_types.py. Import
these aliases back into estimator_configs.py, and keep the private frozensets
_VALID_DENSITY_MODELS and _VALID_CLASSIFIER_MODELS local to the
estimator_configs.py file since they are implementation details for validation.
- Around line 585-591: Update the mixed estimator validation in __post_init__ to
use the accepted fields from _build_mixed_density_estimator together with the
inner continuous-model builder signature, rather than validating only
model_builders[self.continuous_model]. Ensure num_transforms, num_components,
num_bins, and tail_bound are accepted while preserving rejection of unrelated
fields.

In `@tests/build_context_test.py`:
- Line 24: Update each listed test function in tests/build_context_test.py
(lines 24, 38, 45, 69, 151, 158, and 167) and
tests/density_estimator_builder_test.py (lines 16, 21, 28, and 38) with concise
Google-style docstrings describing the behavior under test: z-score defaults,
valid and invalid modes, injected statistics, from_kwargs serialization,
unknown-key warnings, deprecated aliases, invalid model validation, sparse
serialization, extra-key serialization, and build keyword filtering.

---

Nitpick comments:
In `@sbi/neural_nets/net_builders/estimator_configs.py`:
- Around line 57-85: Update _EstimatorBuilderBase.__post_init__ to resolve
annotations with get_type_hints(type(self)) once per builder class, then pass
each resolved field annotation to _literal_values() instead of f.type. Preserve
the existing validation behavior and leave explicit _VALID_* discriminator
checks independent of Field.type.
- Around line 70-76: Update the extra_kwargs field in _EstimatorBuilderBase to
be keyword-only by enabling the dataclass field’s kw_only option, ensuring
positional arguments in estimator builder subclasses bind to fields such as
model instead of extra_kwargs.

In `@sbi/neural_nets/net_builders/flow.py`:
- Line 586: Update the Google-style docstrings for build_zuko_nsf and
build_zuko_ncsf so their num_bins parameter descriptions state a default of 10
instead of 8, matching the current function signatures.

In `@tests/density_estimator_builder_test.py`:
- Around line 71-81: Update
test_density_estimator_builder_build_with_embedding_net to assert that the built
estimator’s embedding_net is the exact emb object supplied to
DensityEstimatorBuilder, replacing the weaker nn.Identity check while preserving
the existing type assertion.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dd87f876-bcb3-4178-94d4-2e26f0464ff8

📥 Commits

Reviewing files that changed from the base of the PR and between 48dcd35 and cc1e1a8.

📒 Files selected for processing (30)
  • sbi/inference/trainers/nle/mnle.py
  • sbi/inference/trainers/nle/nle_a.py
  • sbi/inference/trainers/nle/nle_base.py
  • sbi/inference/trainers/npe/mnpe.py
  • sbi/inference/trainers/npe/npe_a.py
  • sbi/inference/trainers/npe/npe_b.py
  • sbi/inference/trainers/npe/npe_base.py
  • sbi/inference/trainers/npe/npe_c.py
  • sbi/inference/trainers/npe/npe_pfn.py
  • sbi/inference/trainers/nre/bnre.py
  • sbi/inference/trainers/nre/nre_a.py
  • sbi/inference/trainers/nre/nre_b.py
  • sbi/inference/trainers/nre/nre_base.py
  • sbi/inference/trainers/nre/nre_c.py
  • sbi/inference/trainers/vfpe/base_vf_inference.py
  • sbi/inference/trainers/vfpe/fmpe.py
  • sbi/inference/trainers/vfpe/npse.py
  • sbi/neural_nets/__init__.py
  • sbi/neural_nets/build_context.py
  • sbi/neural_nets/estimators/base.py
  • sbi/neural_nets/net_builders/__init__.py
  • sbi/neural_nets/net_builders/estimator_configs.py
  • sbi/neural_nets/net_builders/flow.py
  • sbi/neural_nets/net_builders/mixed_nets.py
  • sbi/neural_nets/net_builders/vector_field_nets.py
  • sbi/utils/user_input_checks.py
  • tests/build_context_test.py
  • tests/density_estimator_builder_test.py
  • tests/npe_nle_builder_integration_test.py
  • tests/nre_builder_integration_test.py

Comment thread tests/build_context_test.py Resolved
@janfb

janfb commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@satwiksps this is the port of your builder PRs (1–5) to main, now that 0.27 has shipped. The six cherry-picks are your commits unchanged.

The three commits on top are mine, from the pre-merge review. Can I ask you for a review?

  • 0e6e0b0: condition-side transform_to_unconstrained was a silent no-op on DensityEstimatorBuilder, so I removed it from the Literal; extra_kwargs is now keyword-only; the trainer guards moved to a per-class _ALLOWED_BUILDER_TYPES, so plain NPE/NLE and MNPE/MNLE each accept only their own builder family.
  • 898b1c8: a test that pins the model argument as the first positional parameter.
  • b35ff0c and cc1e1a8 (earlier): low-level build defaults aligned with the factory, and the x_dist guard.

Two of these change the base class you extend in #1921, so they matter for your retarget: the keyword-only change applies to VectorFieldEstimatorBuilder as well, and I think the same condition-side z-scoring question applies to it. The guard pattern is also what FMPE and NPSE need for wrong-family builders.

cheers, Jan

@janfb
janfb requested a review from satwiksps August 4, 2026 15:07

@satwiksps satwiksps left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Went through all four of your commits on top plus the six cherry-picks. Everything looks good to me.

The extra_kwargs catch is really nice. I reproduced it in my branch VectorFieldEstimatorBuilder("transformer") bound the name to extra_kwargs and quietly left model="mlp". this kw_only on _EstimatorBuilderBase fixes it for every subclass at once, including ones that don't exist yet, and the test pins it so it cant come back. That is a nicer fix than anything I could have written.

Thanks for doing the port and for the review opportunity on top.

@janfb
janfb force-pushed the satwik-builders-to-main branch from 898b1c8 to 12db0e2 Compare August 5, 2026 04:41
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/build_context_test.py`:
- Around line 151-155: Update test_estimator_builder_base_from_kwargs to
construct ConditionalFlowConfig via its from_kwargs() method with
hidden_features=64, then retain the existing to_dict() assertion to verify the
known-field handling contract.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 04ce2612-6649-4aa2-8e72-caf0e8a3a267

📥 Commits

Reviewing files that changed from the base of the PR and between 500483d and 12db0e2.

📒 Files selected for processing (30)
  • sbi/inference/trainers/nle/mnle.py
  • sbi/inference/trainers/nle/nle_a.py
  • sbi/inference/trainers/nle/nle_base.py
  • sbi/inference/trainers/npe/mnpe.py
  • sbi/inference/trainers/npe/npe_a.py
  • sbi/inference/trainers/npe/npe_b.py
  • sbi/inference/trainers/npe/npe_base.py
  • sbi/inference/trainers/npe/npe_c.py
  • sbi/inference/trainers/npe/npe_pfn.py
  • sbi/inference/trainers/nre/bnre.py
  • sbi/inference/trainers/nre/nre_a.py
  • sbi/inference/trainers/nre/nre_b.py
  • sbi/inference/trainers/nre/nre_base.py
  • sbi/inference/trainers/nre/nre_c.py
  • sbi/inference/trainers/vfpe/base_vf_inference.py
  • sbi/inference/trainers/vfpe/fmpe.py
  • sbi/inference/trainers/vfpe/npse.py
  • sbi/neural_nets/__init__.py
  • sbi/neural_nets/build_context.py
  • sbi/neural_nets/estimators/base.py
  • sbi/neural_nets/net_builders/__init__.py
  • sbi/neural_nets/net_builders/estimator_configs.py
  • sbi/neural_nets/net_builders/flow.py
  • sbi/neural_nets/net_builders/mixed_nets.py
  • sbi/neural_nets/net_builders/vector_field_nets.py
  • sbi/utils/user_input_checks.py
  • tests/build_context_test.py
  • tests/density_estimator_builder_test.py
  • tests/npe_nle_builder_integration_test.py
  • tests/nre_builder_integration_test.py
🚧 Files skipped from review as they are similar to previous changes (28)
  • sbi/inference/trainers/vfpe/base_vf_inference.py
  • sbi/neural_nets/net_builders/init.py
  • sbi/inference/trainers/vfpe/fmpe.py
  • sbi/inference/trainers/nle/nle_a.py
  • sbi/neural_nets/net_builders/mixed_nets.py
  • sbi/inference/trainers/nre/nre_c.py
  • tests/density_estimator_builder_test.py
  • sbi/inference/trainers/vfpe/npse.py
  • sbi/inference/trainers/nre/nre_b.py
  • sbi/utils/user_input_checks.py
  • sbi/neural_nets/init.py
  • sbi/inference/trainers/npe/npe_pfn.py
  • sbi/inference/trainers/nre/nre_a.py
  • sbi/inference/trainers/npe/npe_c.py
  • tests/npe_nle_builder_integration_test.py
  • sbi/inference/trainers/nre/bnre.py
  • sbi/neural_nets/build_context.py
  • sbi/inference/trainers/npe/npe_a.py
  • sbi/inference/trainers/nle/mnle.py
  • sbi/neural_nets/net_builders/vector_field_nets.py
  • sbi/inference/trainers/npe/npe_b.py
  • sbi/neural_nets/estimators/base.py
  • sbi/inference/trainers/nre/nre_base.py
  • sbi/inference/trainers/nle/nle_base.py
  • sbi/inference/trainers/npe/mnpe.py
  • sbi/neural_nets/net_builders/flow.py
  • sbi/inference/trainers/npe/npe_base.py
  • sbi/neural_nets/net_builders/estimator_configs.py

Comment on lines +151 to +155
def test_estimator_builder_base_from_kwargs():
"""The existing from_kwargs() + to_dict() contract is preserved."""
cfg = ConditionalFlowConfig(hidden_features=64)
d = cfg.to_dict()
assert d == {"hidden_features": 64}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Exercise from_kwargs() in this test.

Line 153 constructs ConditionalFlowConfig directly. The test does not cover known-field handling through from_kwargs().

Proposed fix
-    cfg = ConditionalFlowConfig(hidden_features=64)
+    cfg = ConditionalFlowConfig.from_kwargs(hidden_features=64)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def test_estimator_builder_base_from_kwargs():
"""The existing from_kwargs() + to_dict() contract is preserved."""
cfg = ConditionalFlowConfig(hidden_features=64)
d = cfg.to_dict()
assert d == {"hidden_features": 64}
def test_estimator_builder_base_from_kwargs():
"""The existing from_kwargs() + to_dict() contract is preserved."""
cfg = ConditionalFlowConfig.from_kwargs(hidden_features=64)
d = cfg.to_dict()
assert d == {"hidden_features": 64}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/build_context_test.py` around lines 151 - 155, Update
test_estimator_builder_base_from_kwargs to construct ConditionalFlowConfig via
its from_kwargs() method with hidden_features=64, then retain the existing
to_dict() assertion to verify the known-field handling contract.

satwiksps and others added 7 commits August 5, 2026 06:55
Ports #1872, which was reviewed and merged into the `gsoc-2026`
branch. See that pull request for the full description.

(cherry picked from commit d0afd1d)
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)
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)
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)
Ports #1912, which was reviewed and merged into the `gsoc-2026`
branch. See that pull request for the full description.

(cherry picked from commit 9373587)
…ents (#1920)

Ports #1920, which was reviewed and merged into the `gsoc-2026`
branch. See that pull request for the full description.

(cherry picked from commit 37d0327)
The builder classes dispatch straight to the build_* functions, so any
default that differed from the factory silently changed the network the
trainers construct. MNLE() and MNPE() had lost capacity this way
(num_transforms 5 -> 2, num_bins 10 -> 5, num_components 10 -> 5).

Aligns num_bins in build_zuko_nsf/ncsf, num_transforms in
build_zuko_gf/bpf, and the three mixed defaults; updates the two num_bins
docstrings that stated the old value.
@janfb
janfb force-pushed the satwik-builders-to-main branch from 12db0e2 to aea7742 Compare August 5, 2026 04:56
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
sbi/neural_nets/net_builders/estimator_configs.py (1)

141-177: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

extra_kwargs can still fail at build time for classifiers without **kwargs.

_reject_inapplicable_fields only checks declared dataclass fields. _build_kwargs merges self.extra_kwargs into the call at Line 126. build_mlp_classifier and build_resnet_classifier declare no **kwargs. An unknown key in extra_kwargs therefore raises TypeError inside the build function during training, not at builder construction.

Consider validating extra_kwargs keys against build_fn when the target function has no VAR_KEYWORD parameter, so the error surfaces at construction time with the same message style.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sbi/neural_nets/net_builders/estimator_configs.py` around lines 141 - 177,
Update _reject_inapplicable_fields to also validate keys in self.extra_kwargs
when build_fn does not accept VAR_KEYWORD arguments; reject unknown keys during
construction using the existing discriminator-aware ValueError message style,
while allowing declared parameters and aliases.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@sbi/inference/trainers/nre/nre_base.py`:
- Around line 493-507: Add Google-style docstrings to `_wrap_builder` and its
nested `build_fn`: document the `builder` parameter and returned callable for
`_wrap_builder`, and document `batch_theta`, `batch_x`, and the returned
`RatioEstimator` for `build_fn`, using the existing type annotations and
behavior.

---

Nitpick comments:
In `@sbi/neural_nets/net_builders/estimator_configs.py`:
- Around line 141-177: Update _reject_inapplicable_fields to also validate keys
in self.extra_kwargs when build_fn does not accept VAR_KEYWORD arguments; reject
unknown keys during construction using the existing discriminator-aware
ValueError message style, while allowing declared parameters and aliases.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 50236b18-26b5-4856-9f8c-6007488ccccc

📥 Commits

Reviewing files that changed from the base of the PR and between 500483d and aea7742.

📒 Files selected for processing (30)
  • sbi/inference/trainers/nle/mnle.py
  • sbi/inference/trainers/nle/nle_a.py
  • sbi/inference/trainers/nle/nle_base.py
  • sbi/inference/trainers/npe/mnpe.py
  • sbi/inference/trainers/npe/npe_a.py
  • sbi/inference/trainers/npe/npe_b.py
  • sbi/inference/trainers/npe/npe_base.py
  • sbi/inference/trainers/npe/npe_c.py
  • sbi/inference/trainers/npe/npe_pfn.py
  • sbi/inference/trainers/nre/bnre.py
  • sbi/inference/trainers/nre/nre_a.py
  • sbi/inference/trainers/nre/nre_b.py
  • sbi/inference/trainers/nre/nre_base.py
  • sbi/inference/trainers/nre/nre_c.py
  • sbi/inference/trainers/vfpe/base_vf_inference.py
  • sbi/inference/trainers/vfpe/fmpe.py
  • sbi/inference/trainers/vfpe/npse.py
  • sbi/neural_nets/__init__.py
  • sbi/neural_nets/build_context.py
  • sbi/neural_nets/estimators/base.py
  • sbi/neural_nets/net_builders/__init__.py
  • sbi/neural_nets/net_builders/estimator_configs.py
  • sbi/neural_nets/net_builders/flow.py
  • sbi/neural_nets/net_builders/mixed_nets.py
  • sbi/neural_nets/net_builders/vector_field_nets.py
  • sbi/utils/user_input_checks.py
  • tests/build_context_test.py
  • tests/density_estimator_builder_test.py
  • tests/npe_nle_builder_integration_test.py
  • tests/nre_builder_integration_test.py
🚧 Files skipped from review as they are similar to previous changes (26)
  • sbi/neural_nets/net_builders/mixed_nets.py
  • sbi/inference/trainers/vfpe/base_vf_inference.py
  • sbi/neural_nets/net_builders/init.py
  • sbi/utils/user_input_checks.py
  • sbi/inference/trainers/npe/npe_a.py
  • sbi/inference/trainers/vfpe/fmpe.py
  • sbi/inference/trainers/nre/nre_b.py
  • sbi/inference/trainers/nre/nre_a.py
  • tests/density_estimator_builder_test.py
  • tests/nre_builder_integration_test.py
  • sbi/inference/trainers/nre/bnre.py
  • sbi/neural_nets/net_builders/vector_field_nets.py
  • sbi/neural_nets/estimators/base.py
  • sbi/inference/trainers/nre/nre_c.py
  • sbi/inference/trainers/npe/npe_b.py
  • sbi/inference/trainers/npe/npe_c.py
  • sbi/neural_nets/init.py
  • sbi/inference/trainers/nle/nle_a.py
  • sbi/neural_nets/net_builders/flow.py
  • sbi/inference/trainers/npe/npe_base.py
  • tests/build_context_test.py
  • sbi/neural_nets/build_context.py
  • sbi/inference/trainers/nle/mnle.py
  • sbi/inference/trainers/npe/npe_pfn.py
  • sbi/inference/trainers/nle/nle_base.py
  • sbi/inference/trainers/vfpe/npse.py

Comment on lines +493 to +507
@staticmethod
def _wrap_builder(
builder: _EstimatorBuilderBase,
) -> Callable:
"""Wrap a builder object as a legacy-compatible build function.

This allows the existing ``_initialize_neural_network`` flow to work
unchanged: the returned callable has the same ``(batch_theta, batch_x)``
signature as the functions produced by ``classifier_nn``.
"""

def build_fn(batch_theta, batch_x):
return builder.build(batch_input=batch_theta, batch_condition=batch_x)

return build_fn

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add Google-style docstrings for both wrapper functions.

_wrap_builder does not document builder or its return value. Nested build_fn has no docstring. Document the builder, both batch arguments, and the returned RatioEstimator.

As per coding guidelines, **/*.py: Use Google-style docstrings for functions and classes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sbi/inference/trainers/nre/nre_base.py` around lines 493 - 507, Add
Google-style docstrings to `_wrap_builder` and its nested `build_fn`: document
the `builder` parameter and returned callable for `_wrap_builder`, and document
`batch_theta`, `batch_x`, and the returned `RatioEstimator` for `build_fn`,
using the existing type annotations and behavior.

Source: Coding guidelines

janfb added 3 commits August 5, 2026 07:01
Two problems with the new builder argument:

A builder for the wrong estimator family fell through to the generic
callable branch and failed later with an unrelated error. Each trainer now
declares the families it accepts in _ALLOWED_BUILDER_TYPES: NPE and NLE
take the plain density builder, MNPE and MNLE the mixed one.

NPE_A defaults density_estimator to the 'mdn_snpe_a' string, so every
NPE_A(prior) call emitted the deprecation warning for a value the user
never passed. NPE_A now resolves its own default to a build function
before the base class inspects the argument.

Also widens the check_estimator_arg annotation to cover builders.
…lders

The zuko flows support an unconstraining transform in place of z-scoring,
but the builders offered no way to select it and no way to pass the
required support distribution. Adds x_dist to both density builders and
allows transform_to_unconstrained on the input side.

The condition side is deliberately excluded: the build functions validate
and apply the transform for the input only, so accepting it for the
condition would silently do nothing.
Two arguments did not behave as their names and positions implied, and
both built a different network than the user asked for, without an error.

The NRE builder exposed the build functions' positional x/y naming, in
which embedding_net_x applies to theta. A user following classifier_nn
therefore embedded the parameters with the net meant for the data. The
fields are now embedding_net_theta and embedding_net_x, matching
classifier_nn and the attributes of the built RatioEstimator, and
_build_kwargs translates them.

extra_kwargs is declared on the shared base class, so it was the first
positional parameter of every builder: DensityEstimatorBuilder("nsf")
bound the model name to extra_kwargs and silently built the default MAF.
It is now keyword-only.

Both embedding tests assert the supplied module is installed in the named
slot, and a new test pins the model as the first positional argument of
all three builders.
@janfb
janfb force-pushed the satwik-builders-to-main branch from aea7742 to 2031a40 Compare August 5, 2026 05:02
@janfb
janfb merged commit 8c6f1ea into main Aug 5, 2026
18 checks passed
@janfb
janfb deleted the satwik-builders-to-main branch August 5, 2026 05:07
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