Skip to content

Add per-model marginal configs for MarginalTrainer - #1975

Merged
janfb merged 21 commits into
sbi-dev:mainfrom
satwiksps:marginal-builder-clean
Aug 12, 2026
Merged

janfb merged 21 commits into
sbi-dev:mainfrom
satwiksps:marginal-builder-clean

Conversation

@satwiksps

@satwiksps satwiksps commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

This PR continues the GSoC 2026 Neural Network Builder API refactor by adding config classes for MarginalTrainer. It is the first PR that uses the new per-model design we agreed on, so instead of one flat builder class for the whole family, every model gets its own small class.

Instead of passing a string like MarginalTrainer(density_estimator="nsf"), we can now pass a typed config like MarginalTrainer(density_estimator=MarginalNSFConfig(num_transforms=8)). There is one class for each of the nine unconditional Zuko flows (BPF, GF, MAF, NAF, NCSF, NICE, NSF, SOSPF, UNAF). Each class only carries the fields its own flow actually accepts, so writing a setting that the model does not use is a plain TypeError from Python at construction time. We do not need _reject_inapplicable_fields, whitelists or the sync tests that come with them.

While doing this I, with the help of Claude Opus 5, found that num_bins never actually reached the flow. build_zuko_unconditional_flow drops num_bins before it gets to Zuko, so marginal_nn's documented num_bins=10 had no effect and a marginal NSF always used Zuko's own default of 8 bins. The new configs use Zuko's own name bins, so the value arrives now. Marginal NSF and NCSF default to 10 bins, which is what the conditional path already uses. This means the network changes for existing users, so I am flagging it clearly below.

The trainer default also moves from ZukoFlowType.NSF to None, which then resolves to MarginalNSFConfig(). Without this every plain MarginalTrainer() would hit the new deprecation warning. FMPE and NPSE did the same thing in vf builder PR. Passing a string or a ZukoFlowType still works but now warns, and a callable still works as before.

Does this close any issues?

N/A

Anything else we should know?

Some questions

Marginal NSF and NCSF now use 10 bins instead of 8. This is the num_bins bug fix described above and was suggested by Claude, I think this make sense, right?
The side effect is that MarginalTrainer("nsf") now gets 10 bins while marginal_nn(ZukoFlowType.NSF) still gets 8, until PR 8 retires the factory. This follows per-model-config-plan.md (the dict resolves the deprecated string path), but it is different from what my earlier design note said, so tell me if you would rather keep the string going through marginal_nn.

b80b28f failed but 8432b0c passes so most probably a flake then. marginal_estimator_test draws its mixture target with torch.randn(2) torch.rand(2) inside parametrise decorator so before set_seed runs parameters are picked at collection and every CI run tests a different distribution, should we replace random draw with fixed parameters ?

The marginal configs use z_score_x but every other builder uses z_score_input after the Decision 17 rename, so this is the only place with the old style name, we should update this too right ?

AI Usage

Claude Opus 5 via Claude Code CLI was used to verify the commits before final push. Many suggestions like dropped num_bins fix, docstring and comments and minor code logic improvements were accepted.

Checklist

  • I have read the contributing guide.
  • uv run pytest -n auto -m "not slow and not gpu" passes.
  • uv run pre-commit run --all-files passes (ruff and formatting).
  • uv run pyright sbi passes.
  • I added or updated tests for the changed behavior.
  • I used Google-style docstrings for new or changed public functions.
  • (If applicable) I reported how long new tests run and marked slow ones
    with pytest.mark.slow.

@coderabbitai

coderabbitai Bot commented Aug 10, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 600dc812-4cfb-4775-b3d7-b1e480606ce7

📥 Commits

Reviewing files that changed from the base of the PR and between b22cbf2 and c69157e.

📒 Files selected for processing (1)
  • tests/marginal_builder_integration_test.py

📝 Walkthrough

Walkthrough

Marginal estimators now use typed configuration objects. MarginalTrainer builds configured unconditional flows, supports deprecated legacy inputs, rejects invalid builders, and exposes the configurations publicly. Tests and examples use the new API.

Changes

Marginal estimator configuration API

Layer / File(s) Summary
Marginal configuration models
sbi/neural_nets/net_builders/estimator_configs.py
Adds shared and model-specific configurations, validation, parameter forwarding, flow construction, model mappings, and case-insensitive lookup.
Trainer integration and public exports
sbi/inference/trainers/marginal/marginal_base.py, sbi/neural_nets/__init__.py, sbi/neural_nets/net_builders/__init__.py
Updates MarginalTrainer input handling, preserves legacy inputs with warnings, rejects invalid builders, and exports the new classes.
Integration, compatibility, and examples
tests/marginal_builder_integration_test.py, tests/marginal_estimator_test.py, tests/misspecification_test.py, docs/advanced_tutorials/21_diagnostics_misspecification_checks.ipynb, docs/how_to_guide/18_model_misspecification.ipynb
Covers configuration validation, construction, trainer compatibility, callable builders, training, and updated usage examples.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MarginalTrainer
  participant MarginalConfigBase
  participant ZukoUnconditionalFlow
  MarginalTrainer->>MarginalConfigBase: build(batch_x)
  MarginalConfigBase->>ZukoUnconditionalFlow: construct configured flow
  ZukoUnconditionalFlow-->>MarginalTrainer: return density estimator
Loading

Possibly related PRs

  • sbi-dev/sbi#1957: Refactors estimator configuration patterns, public exports, and trainer validation around builder/configuration objects.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding per-model marginal configuration classes for MarginalTrainer.
Description check ✅ Passed The description follows the template, explains the changes and impact, records issue status, documents AI use, and completes the checklist.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 1

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

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

Add Google-style docstrings to the new methods.

Add a docstring to __post_init__ and __repr__. As per coding guidelines, **/*.py: Use Google-style docstrings for functions and classes.

Also applies to: 953-953

🤖 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` at line 930, Add concise
Google-style docstrings to the new __post_init__ and __repr__ methods,
documenting their purpose and behavior according to the project’s Python
documentation guidelines.

Source: Coding guidelines

🤖 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 946-951: Update the unconditional-flow configuration/build path
around build_zuko_unconditional_flow to reject extra_kwargs keys that the
builder removes, including num_bins, or translate supported aliases such as
num_bins to bins before constructing the Zuko flow. Ensure requested values are
never silently ignored, and add a regression test covering
MarginalNSFConfig(extra_kwargs={"num_bins": 20}).

---

Nitpick comments:
In `@sbi/neural_nets/net_builders/estimator_configs.py`:
- Line 930: Add concise Google-style docstrings to the new __post_init__ and
__repr__ methods, documenting their purpose and behavior according to the
project’s Python documentation guidelines.
🪄 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: b5844bf2-f5ca-415b-8f48-09388f884c71

📥 Commits

Reviewing files that changed from the base of the PR and between 94c9a7c and d7945f7.

📒 Files selected for processing (7)
  • sbi/inference/trainers/marginal/marginal_base.py
  • sbi/neural_nets/__init__.py
  • sbi/neural_nets/net_builders/__init__.py
  • sbi/neural_nets/net_builders/estimator_configs.py
  • tests/marginal_builder_integration_test.py
  • tests/marginal_estimator_test.py
  • tests/misspecification_test.py

@codecov

codecov Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.47%. Comparing base (94c9a7c) to head (c69157e).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1975      +/-   ##
==========================================
+ Coverage   87.68%   88.47%   +0.79%     
==========================================
  Files         140      140              
  Lines       13987    14095     +108     
==========================================
+ Hits        12264    12471     +207     
+ Misses       1723     1624      -99     
Flag Coverage Δ
fast 84.10% <100.00%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/trainers/marginal/marginal_base.py 94.54% <100.00%> (+1.03%) ⬆️
sbi/neural_nets/__init__.py 100.00% <ø> (ø)
sbi/neural_nets/net_builders/__init__.py 100.00% <ø> (ø)
sbi/neural_nets/net_builders/estimator_configs.py 99.75% <100.00%> (+0.74%) ⬆️

... and 25 files with indirect coverage changes

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

thanks @satwiksps, very clean PR. Just a couple of small things to fix, see inline.

One thing not in the diff: the how to guide 18_model_misspecification.ipynb:42 now raises your FutureWarning, so the guide teaches the deprecated path and prints the warning in its output. Please update it, and the two cells in docs/advanced_tutorials/21_diagnostics_misspecification_checks.ipynb (lines 398 and 1370).



@dataclass(frozen=True, eq=False, repr=False)
class MarginalGFConfig(MarginalConfigBase):

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.

GF still accepts a setting that it then ignores, which is what these classes should make impossible.

Zuko's GF passes its **kwargs to ElementWiseTransform, and with context=0 (always the case for a marginal flow) those kwargs are dropped. So hidden_features never arrives:

x = torch.randn(64, 3)
for h in (10, 50, 200):
    m = MarginalGFConfig(hidden_features=h).build(x)
    print(h, sum(p.numel() for p in m.parameters()))   # 276, 276, 276

The same mechanism makes extra_kwargs silent here: MarginalGFConfig(extra_kwargs={"nonsense": 1}).build(x) builds fine, while the other eight models raise TypeError. Your typo test only covers NSF.

Please make this fail at construction. MarginalGFConfig(hidden_features=...) should raise, with a message that says GF ignores it.


hidden_features: Union[int, Sequence[int]] = 50
num_transforms: int = 5
z_score_x: Literal["none", "independent", "structured"] = "independent"

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 question in the description, and you are right. Every other builder takes
z_score_input and maps it to the build function's z_score_x through
_BUILD_KWARG_ALIASES at line 57. My sketch in the design note caused this.

Please rename it to z_score_input and translate through that map rather than adding a
second one.

"marginal models. Use a per-model config, e.g. "
"MarginalNSFConfig()."
)
# Python does not check `Literal` values at runtime.

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 loop already exists at lines 87-95 in _EstimatorBuilderBase. The only difference is the val is not None guard, which that base needs because it uses None for "not set" and yours does not.

Please move it into one module-level function with a flag and call it from both. PR 7.5 would otherwise write a third copy.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

will update this in PR 7.5 too 👍

d.update(self.extra_kwargs)
return d

def build(self, batch_x: Tensor) -> UnconditionalDensityEstimator:

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.

build_zuko_unconditional_flow returns a ZukoUnconditionalFlow, and every config goes through it, so this always returns that type — your docstring two lines down says so. Please narrow the annotation.



@dataclass(frozen=True, eq=False, repr=False)
class _ZukoSplineFields:

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.

Please inline these three Field blocks into the leaf classes and delete them.

They cost 26 lines and save 7 field declarations. They do not save the documentation either: every leaf still documents the inherited field in its own Args: section. And _ZukoSplineFields has no future use, because the conditional builders spell it num_bins and rename it internally.

There is also a trap worth removing before PR 7.5 copies the pattern twenty times. Dataclass field order comes from the reverse MRO, so writing class X(MarginalConfigBase, _ZukoSplineFields) puts bins first and shifts every positional argument, without an error.

posterior_parameters.py is our precedent: 7 frozen dataclasses, no mixins, max_sampling_batch_size=10000 written out in 5 of them.

_WHICH_NF: ClassVar[str] = "UNAF"


MARGINAL_MODELS = Literal[

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.

Two small things. Please put this on one line if possible, like CLASSIFIER_MODELS (632) and VF_MODELS (712).
And please have test_every_model_has_a_config compare it against _MARGINAL_CONFIGS: the other three lists cannot drift because each has a derived companion (_VALID_DENSITY_MODELS at 424, and the same at 634 and 714), while yours is two hand-written lists with nothing checking them.

"config_cls,kwargs",
[
(MarginalMAFConfig, {"bins": 20}),
(MarginalNSFConfig, {"randperm": True}),

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.

randperm is the wrong example. Zuko's NSF subclasses its MAF, so it does accept it: MarginalNSFConfig(extra_kwargs={"randperm": True}).build(batch_x) builds a different network. BPF, NCSF and SOSPF are the same.

Your config is still right, since build_zuko_nsf does not expose randperm either. Only the test claims something false, and a claim in a test docstring gets read later as fact. randmask is a genuine NICE-only setting and raises the TypeError you want.

MarginalTrainer(density_estimator=density_estimator)


@pytest.mark.parametrize("case", [str.lower, str.upper], ids=["lower", "upper"])

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.

Please drop this axis. Every key in _MARGINAL_CONFIGS is lowercase, so str.lower is the identity here and 9 of the 18 cases re-test one .lower() call, at 18 network builds.

Two more of the same kind: test_configs_are_immutable runs 9 times over one code path (a dataclass cannot inherit non-frozen from frozen, so a non-frozen leaf would not import), and the config and configured cases in test_no_warning_for_valid_inputs reach the same dispatch branch.

Comment thread tests/marginal_estimator_test.py Outdated

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.

Your diagnosis is right. This runs at collection time, before the autouse set_seed fixture in tests/conftest.py:27, and torch's global RNG is not seeded at that point. So every run tests a different mixture, and torch.rand(2) can draw a scale near zero. Please use fixed values.

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

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

1048-1061: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a Google-style docstring to MarginalGFConfig.__post_init__.

Document that this method rejects settings that unconditional GF flows ignore. Include the ValueError condition.

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

Proposed fix
     def __post_init__(self):
+        """Validate settings that an unconditional GF flow would ignore.
+
+        Raises:
+            ValueError: If `hidden_features` differs from its default or if
+                `extra_kwargs` is not empty.
+        """
         super().__post_init__()
🤖 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 1048 - 1061,
Add a Google-style docstring to MarginalGFConfig.__post_init__ describing that
it rejects hidden_features and extra_kwargs settings ignored by unconditional GF
flows, and document that it raises ValueError when either unsupported setting is
provided. Preserve the existing validation behavior unchanged.

Source: Coding guidelines

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

Nitpick comments:
In `@sbi/neural_nets/net_builders/estimator_configs.py`:
- Around line 1048-1061: Add a Google-style docstring to
MarginalGFConfig.__post_init__ describing that it rejects hidden_features and
extra_kwargs settings ignored by unconditional GF flows, and document that it
raises ValueError when either unsupported setting is provided. Preserve the
existing validation behavior unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 56e6bbbe-e250-4df4-862b-516a58d0d449

📥 Commits

Reviewing files that changed from the base of the PR and between 8432b0c and b22cbf2.

📒 Files selected for processing (6)
  • docs/advanced_tutorials/21_diagnostics_misspecification_checks.ipynb
  • docs/how_to_guide/18_model_misspecification.ipynb
  • sbi/inference/trainers/marginal/marginal_base.py
  • sbi/neural_nets/net_builders/estimator_configs.py
  • tests/marginal_builder_integration_test.py
  • tests/marginal_estimator_test.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/marginal_estimator_test.py
  • tests/marginal_builder_integration_test.py
  • sbi/inference/trainers/marginal/marginal_base.py

@satwiksps
satwiksps requested a review from janfb August 12, 2026 12:53

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

@janfb
janfb merged commit 70b9a81 into sbi-dev:main Aug 12, 2026
17 checks passed
@janfb
janfb deleted the marginal-builder-clean branch August 12, 2026 13:16
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