Repository navigation
Add VectorFieldEstimatorBuilder for FMPE / NPSE trainers - #1921
Conversation
3e8f552 to
2896bdc
Compare
df54baf to
900a7bf
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1921 +/- ##
==========================================
+ Coverage 89.21% 89.31% +0.10%
==========================================
Files 140 140
Lines 13895 13987 +92
==========================================
+ Hits 12396 12493 +97
+ Misses 1499 1494 -5
Flags with carried forward coverage won't be shown. Click here to find out more.
|
4b6e717 to
57d7dc2
Compare
57d7dc2 to
ef5d3a6
Compare
|
Hi @janfb, fix: clone base distribution parameters to avoid memory overlap in lo… for bug in also I hope the remaining CI failures could be fixed when |
|
Hi @satwiksps, thanks for the detailed comment. I will do the full review later today, but one thing upfront because it explains your CI failures:
I think the cleanest fix is at the root: change the defaults in z_score_x: Optional[str] = "independent", That matches all other low-level net builders (build_maf etc.), and posterior_flow_nn / posterior_score_nn pass these explicitly anyway, so nothing else changes. This is also why the c2st test fails (it uses default FMPE(prior) on unstandardized data) and why the load_state_dict crash appeared: with z-scoring off, mean_0 is a scalar, and the broadcast_to view then has overlapping memory. So merging main won't fix your CI — this will. Keep the .clone() though, that fix is correct either way. Please also add a small regression test that the default builder produces a standardizing net, so this can't slip through again. Cheers, Jan |
63b62e9 to
ddde810
Compare
janfb
left a comment
There was a problem hiding this comment.
well done! this is a very complex PR due to the complexity of the VF kwargs. I noticed a couple of general design issues, but they are beyond the scope of this PR, so I suggest to fix the obvious problems here now, see my comments.
|
All tests pass now, thank you Jan, for helping me find hidden errors 🙌. Once the cherry picked PRs are merged in to |
c9443a6 to
ef50ece
Compare
|
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:
📝 WalkthroughWalkthroughThis change adds ChangesVector-field estimator builder integration
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant FMPE_or_NPSE
participant VectorFieldTrainer
participant VectorFieldEstimatorBuilder
participant build_vector_field_estimator
FMPE_or_NPSE->>VectorFieldTrainer: provide estimator configuration
VectorFieldTrainer->>VectorFieldEstimatorBuilder: validate and normalize builder
VectorFieldTrainer->>VectorFieldEstimatorBuilder: pass ordered input and condition batches
VectorFieldEstimatorBuilder->>build_vector_field_estimator: dispatch estimator type and network
build_vector_field_estimator-->>VectorFieldEstimatorBuilder: return ConditionalVectorFieldEstimator
VectorFieldEstimatorBuilder-->>VectorFieldTrainer: provide configured estimator
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
sbi/inference/trainers/vfpe/npse.py (1)
109-111: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUpdate the
sde_typedocumentation to match the new behavior.The text says
sde_typeis "Only used whenvf_estimatoris a string (i.e. when using the default builder)". Three cases now exist:
vf_estimator is None:sde_typeis forwarded to the defaultVectorFieldEstimatorBuilder(Line 167).vf_estimatoris aVectorFieldEstimatorBuilder: a non-defaultsde_typeraisesValueError(Line 156). Setsde_typeon the builder.vf_estimatoris a string:sde_typeis forwarded toposterior_score_nn(Line 199).State these cases so users know where to set the value.
🤖 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/vfpe/npse.py` around lines 109 - 111, Update the sde_type parameter documentation near the trainer configuration to describe all three behaviors: when vf_estimator is None, it is forwarded to the default VectorFieldEstimatorBuilder; when vf_estimator is a VectorFieldEstimatorBuilder, non-default sde_type raises ValueError and must be configured on the builder; and when vf_estimator is a string, it is forwarded to posterior_score_nn.sbi/neural_nets/net_builders/vector_field_nets.py (2)
171-173: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winDocumented architecture name does not match the accepted literal.
VF_MODELSdefines"transformer_cross_attn", andbuild_vector_field_estimatorraisesValueError: Unknown architecturefor any other value. Three docstrings still advertise'transformer_cross_attention', so a user who copies the documented name hits that error.
sbi/neural_nets/net_builders/vector_field_nets.py#L171-L173: change"transformer_cross_attention"to"transformer_cross_attn"in thenetargument description.sbi/neural_nets/factory.py#L378-L378: change'transformer_cross_attention'to'transformer_cross_attn'in theposterior_score_nnmodel list.sbi/neural_nets/factory.py#L469-L469: change'transformer_cross_attention'to'transformer_cross_attn'in theposterior_flow_nnmodel list.🤖 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/vector_field_nets.py` around lines 171 - 173, Replace the outdated transformer architecture name with “transformer_cross_attn” in the net argument description of vector_field_nets.py and in the posterior_score_nn and posterior_flow_nn model lists in factory.py at the specified ranges, keeping all other documented architecture names unchanged.
230-246: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRemove duplicate
is_x_emb_seqforwarding.When
posterior_flow_nnorposterior_score_nnreceivesis_x_emb_seq, the transformer call raisesTypeError: got multiple values for keyword argument 'is_x_emb_seq'. Remove the key from forwarded kwargs while preserving the caller-provided value.🤖 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/vector_field_nets.py` around lines 230 - 246, Update the transformer branch around build_transformer_network so is_x_emb_seq is removed from kwargs before forwarding, while preserving and using the caller-provided value when present; retain the existing net-based default for callers that omit it and avoid passing the argument twice.
🧹 Nitpick comments (3)
sbi/neural_nets/net_builders/estimator_configs.py (1)
744-751: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCorrect the dispatch names in the class docstring.
The docstring states that
build()dispatches tobuild_flow_matching_estimatororbuild_score_matching_estimator.build()callsbuild_vector_field_estimatorand passesestimator_type. Update the text so readers can follow the actual call path.📝 Proposed docstring fix
matching). The ``estimator_type`` field selects between the two: - ``"flow"`` dispatches to ``build_flow_matching_estimator`` and - ``"score"`` dispatches to ``build_score_matching_estimator``. + ``build()`` forwards it to ``build_vector_field_estimator``, which + constructs a ``FlowMatchingEstimator`` for ``"flow"`` and a + ``ConditionalScoreEstimator`` subclass for ``"score"``. """🤖 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 744 - 751, Update the class docstring’s dispatch description to reference build_vector_field_estimator as the method called by build(), while retaining that estimator_type selects between flow and score behavior.tests/vf_builder_integration_test.py (1)
172-177: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the unused
gaussian_simsargument.
test_builder_role_shapesbuilds its ownprior,theta, andxat Lines 175-177. Thegaussian_simsfixture is requested but never used, so the fixture runs for no reason.♻️ Proposed cleanup
`@pytest.mark.parametrize`("trainer_cls", [FMPE, NPSE]) -def test_builder_role_shapes(trainer_cls, gaussian_sims): +def test_builder_role_shapes(trainer_cls): """Asymmetric dims catch silent role swaps (Decision 10/13).""" prior = MultivariateNormal(zeros(2), torch.eye(2))🤖 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/vf_builder_integration_test.py` around lines 172 - 177, Remove the unused gaussian_sims parameter from test_builder_role_shapes and its parametrized test signature, leaving the locally constructed prior, theta, and x data unchanged.sbi/inference/trainers/vfpe/npse.py (1)
155-162: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider a sentinel default for
sde_typeto detect an explicit value.The conflict check treats
sde_type != "ve"as "the caller passedsde_type". A caller who passessde_type="ve"explicitly together with a builder that setssde_type="vp"gets no error, and the builder value wins silently. A sentinel default (for examplesde_type: Optional[...] = None) would let you detect an explicit value exactly and keep"ve"as the resolved default. This is optional; the current behavior already documents builder precedence.🤖 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/vfpe/npse.py` around lines 155 - 162, Update the trainer’s sde_type handling around the VectorFieldEstimatorBuilder conflict check to use a sentinel or None default that distinguishes omitted from explicitly provided values, including explicit "ve". Preserve "ve" as the resolved default when sde_type is omitted, while raising for any explicitly supplied value that conflicts with the builder’s sde_type.
🤖 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/vfpe/base_vf_inference.py`:
- Around line 376-380: Reset _best_val_loss, _epochs_since_last_improvement, and
_best_model_state_dict at epoch 0 for non-resumed training runs instead of
relying on hasattr, while preserving them when resume_training is true. Record
the resume state before the training loop and update the convergence-state
initialization in the surrounding training method so a fresh run cannot load a
prior run’s checkpoint.
In `@sbi/neural_nets/net_builders/estimator_configs.py`:
- Around line 703-707: Move the public VF_MODELS type alias from
estimator_configs.py into sbi_types.py, then import or re-export it in
estimator_configs.py so existing consumers remain compatible. Keep
_VALID_VF_MODELS defined locally in estimator_configs.py using the relocated
alias.
In `@tests/vf_builder_integration_test.py`:
- Around line 258-285: Update test_default_builder_applies_z_scoring to validate
the score estimator’s actual input-normalization statistics, mean_0 and std_0,
rather than using _mean_base and _std_base for non-flow estimators. Keep the
existing flow assertions and embedding_net Standardize check unchanged.
---
Outside diff comments:
In `@sbi/inference/trainers/vfpe/npse.py`:
- Around line 109-111: Update the sde_type parameter documentation near the
trainer configuration to describe all three behaviors: when vf_estimator is
None, it is forwarded to the default VectorFieldEstimatorBuilder; when
vf_estimator is a VectorFieldEstimatorBuilder, non-default sde_type raises
ValueError and must be configured on the builder; and when vf_estimator is a
string, it is forwarded to posterior_score_nn.
In `@sbi/neural_nets/net_builders/vector_field_nets.py`:
- Around line 171-173: Replace the outdated transformer architecture name with
“transformer_cross_attn” in the net argument description of vector_field_nets.py
and in the posterior_score_nn and posterior_flow_nn model lists in factory.py at
the specified ranges, keeping all other documented architecture names unchanged.
- Around line 230-246: Update the transformer branch around
build_transformer_network so is_x_emb_seq is removed from kwargs before
forwarding, while preserving and using the caller-provided value when present;
retain the existing net-based default for callers that omit it and avoid passing
the argument twice.
---
Nitpick comments:
In `@sbi/inference/trainers/vfpe/npse.py`:
- Around line 155-162: Update the trainer’s sde_type handling around the
VectorFieldEstimatorBuilder conflict check to use a sentinel or None default
that distinguishes omitted from explicitly provided values, including explicit
"ve". Preserve "ve" as the resolved default when sde_type is omitted, while
raising for any explicitly supplied value that conflicts with the builder’s
sde_type.
In `@sbi/neural_nets/net_builders/estimator_configs.py`:
- Around line 744-751: Update the class docstring’s dispatch description to
reference build_vector_field_estimator as the method called by build(), while
retaining that estimator_type selects between flow and score behavior.
In `@tests/vf_builder_integration_test.py`:
- Around line 172-177: Remove the unused gaussian_sims parameter from
test_builder_role_shapes and its parametrized test signature, leaving the
locally constructed prior, theta, and x data unchanged.
🪄 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: 6ede3170-336e-445a-9c80-4ca2e5afea2d
📒 Files selected for processing (13)
sbi/inference/trainers/base.pysbi/inference/trainers/nle/nle_base.pysbi/inference/trainers/npe/npe_base.pysbi/inference/trainers/nre/nre_base.pysbi/inference/trainers/vfpe/base_vf_inference.pysbi/inference/trainers/vfpe/fmpe.pysbi/inference/trainers/vfpe/npse.pysbi/neural_nets/__init__.pysbi/neural_nets/factory.pysbi/neural_nets/net_builders/__init__.pysbi/neural_nets/net_builders/estimator_configs.pysbi/neural_nets/net_builders/vector_field_nets.pytests/vf_builder_integration_test.py
💤 Files with no reviewable changes (1)
- sbi/inference/trainers/npe/npe_base.py
There was a problem hiding this comment.
🧹 Nitpick comments (1)
tests/vf_builder_integration_test.py (1)
335-367: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd a rejection test for 2-D cross-attention conditions. When
net="transformer_cross_attn"receives 2-Dbatch_y, assertValueErrorwith the documented sequence-shape message.🤖 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/vf_builder_integration_test.py` around lines 335 - 367, Extend test_all_architectures_build with a case where transformer_cross_attn receives 2-D batch_y and assert build_vector_field_estimator raises ValueError containing the documented sequence-shape message. Keep the existing valid 3-D cross-attention case unchanged.
🤖 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 `@tests/vf_builder_integration_test.py`:
- Around line 335-367: Extend test_all_architectures_build with a case where
transformer_cross_attn receives 2-D batch_y and assert
build_vector_field_estimator raises ValueError containing the documented
sequence-shape message. Keep the existing valid 3-D cross-attention case
unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 15be97a6-e56f-4265-8f98-512e8460418a
📒 Files selected for processing (3)
sbi/inference/trainers/vfpe/base_vf_inference.pysbi/inference/trainers/vfpe/npse.pytests/vf_builder_integration_test.py
🚧 Files skipped from review as they are similar to previous changes (2)
- sbi/inference/trainers/vfpe/base_vf_inference.py
- sbi/inference/trainers/vfpe/npse.py
janfb
left a comment
There was a problem hiding this comment.
Almost done, two things remain, see comments.
This reverts commit 4dd7876.
`posterior_flow_nn(z_score_theta=None)` does not disable z-scoring any more. The config layer drops `None` fields as "unset", and #1921 changed the `build_vector_field_estimator` default from `None` to "independent". The parametrization thus trained a z-scored network, and the strict xfail became an XPASS on all Python versions. "none" disables z-scoring, so the case again tests what its id says. The xfail stays valid: FMPE without z-scoring gives C2ST 0.61 on the shifted data.
What does this PR do?
This PR continues the GSoC 2026 Neural Network Builder API refactor by introducing the
VectorFieldEstimatorBuilderfor both vector field trainers (FMPE&NPSE).Instead of passing a string like
vf_estimator="mlp"and configuring everything through factory functions, users can now pass a fully typed builder:VectorFieldEstimatorBuilder(model="mlp", hidden_features=128). The builder covers all four network architectures (mlp,ada_mlp,transformer,transformer_cross_attn) and provides immediate validation — passing score-only arguments (likebeta_min) to a flow-matching builder, architecture-specific fields to the wrong model (likenum_headsfor"mlp"), orsde_typemismatches all fail fast with helpful error messages.The
estimator_typefield defaults toNoneand is automatically resolved by the trainer (FMPE→"flow",NPSE→"score"), so users don't need to specify it unless they want explicit control. This bringsFMPEandNPSEfully in line with the builder pattern previously added forNPE,NLE, andNRE.Files Changed
estimator_configs.py: Added theVectorFieldEstimatorBuilderfrozen dataclass with full typing,estimator_type/sde_typefield guards, and per-architecture validation via_reject_inapplicable_fields.vector_field_nets.py: Fixedtime_emb_typedefault to"sinusoidal"for parity with the factory path.fmpe.py&npse.py: Updated the trainers to acceptVectorFieldEstimatorBuilder, resolveestimator_type=None, and reject mismatched types. Passing a string is still supported but emits aFutureWarning.base_vf_inference.py: RemovedNonefrom the base class signature and deleted the unreachable branch (subclasses own the default).trainers/base.py: Lifted_wrap_builderintoNeuralInference, fixed docstring typo, and typed thebuilderparameter.nre_base.py: Removed the duplicate_wrap_builder(identical to the inherited base version).score_estimator.py: Fixed overlapping-memory crash by cloningmean_0/std_0in the score estimator constructor.tests/vf_builder_integration_test.py: Added tests for builder integration,estimator_typeauto-resolution, cross-trainer rejection, per-architecture validation, conflict guards, and deprecation warnings.AI Usage
Used Grammarly for PR description refinement, VS Code Copilot for code suggestions, and GPT OSS via Antigravity for docstrings and cosmetic updates. Some tests were improved during review by Claude Opus 4.6 via Antigravity.
Does this close any issues?
N/A