Repository navigation
Add per-model marginal configs for MarginalTrainer - #1975
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughMarginal estimators now use typed configuration objects. ChangesMarginal estimator configuration API
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
sbi/neural_nets/net_builders/estimator_configs.py (1)
930-930: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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
📒 Files selected for processing (7)
sbi/inference/trainers/marginal/marginal_base.pysbi/neural_nets/__init__.pysbi/neural_nets/net_builders/__init__.pysbi/neural_nets/net_builders/estimator_configs.pytests/marginal_builder_integration_test.pytests/marginal_estimator_test.pytests/misspecification_test.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more.
|
janfb
left a comment
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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, 276The 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" |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
will update this in PR 7.5 too 👍
| d.update(self.extra_kwargs) | ||
| return d | ||
|
|
||
| def build(self, batch_x: Tensor) -> UnconditionalDensityEstimator: |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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[ |
There was a problem hiding this comment.
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}), |
There was a problem hiding this comment.
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"]) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
sbi/neural_nets/net_builders/estimator_configs.py (1)
1048-1061: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd a Google-style docstring to
MarginalGFConfig.__post_init__.Document that this method rejects settings that unconditional GF flows ignore. Include the
ValueErrorcondition.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
📒 Files selected for processing (6)
docs/advanced_tutorials/21_diagnostics_misspecification_checks.ipynbdocs/how_to_guide/18_model_misspecification.ipynbsbi/inference/trainers/marginal/marginal_base.pysbi/neural_nets/net_builders/estimator_configs.pytests/marginal_builder_integration_test.pytests/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
janfb
left a comment
There was a problem hiding this comment.
Looks good, thanks @satwiksps 👏
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 likeMarginalTrainer(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 plainTypeErrorfrom 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_binsnever actually reached the flow.build_zuko_unconditional_flowdropsnum_binsbefore it gets to Zuko, somarginal_nn's documentednum_bins=10had no effect and a marginal NSF always used Zuko's own default of 8 bins. The new configs use Zuko's own namebins, 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.NSFtoNone, which then resolves toMarginalNSFConfig(). Without this every plainMarginalTrainer()would hit the new deprecation warning. FMPE and NPSE did the same thing in vf builder PR. Passing a string or aZukoFlowTypestill 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_binsbug 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 whilemarginal_nn(ZukoFlowType.NSF)still gets 8, until PR 8 retires the factory. This followsper-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 throughmarginal_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_xbut every other builder usesz_score_inputafter 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
uv run pytest -n auto -m "not slow and not gpu"passes.uv run pre-commit run --all-filespasses (ruff and formatting).uv run pyright sbipasses.with
pytest.mark.slow.