Skip to content

Refactor vectorfield kwargs - #1777

Merged
janfb merged 5 commits into
mainfrom
refactor-vectorfield-kwargs
Feb 24, 2026
Merged

janfb merged 5 commits into
mainfrom
refactor-vectorfield-kwargs

Conversation

@janfb

@janfb janfb commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor

fixing kwargs issues in VF methods and adds a couple of edge case fixes for the time schedules.

See #1775 for context

closing #1775

Note: I introduce a new config dataclass for all VF parameters. it is used only internally and basically only for validating user-passed args and raising errors on typos or unknown args. Alternatively, we could do this manually by defining a dict or sequence of known args for each option, but I like the dataclass approach better and we could eventually use it a public config at a later point.

@codecov

codecov Bot commented Feb 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.50649% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.77%. Comparing base (d41efa6) to head (aa3e824).
⚠️ Report is 1 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/inference/trainers/vfpe/npse.py 57.14% 3 Missing ⚠️
sbi/neural_nets/__init__.py 0.00% 1 Missing ⚠️
sbi/neural_nets/estimators/score_estimator.py 94.11% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1777      +/-   ##
==========================================
+ Coverage   87.65%   87.77%   +0.12%     
==========================================
  Files         140      140              
  Lines       12178    12224      +46     
==========================================
+ Hits        10675    10730      +55     
+ Misses       1503     1494       -9     
Flag Coverage Δ
fast 83.42% <93.50%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/trainers/vfpe/base_vf_inference.py 92.76% <100.00%> (-0.05%) ⬇️
sbi/inference/trainers/vfpe/fmpe.py 91.30% <100.00%> (+0.82%) ⬆️
sbi/neural_nets/estimators/base.py 74.60% <100.00%> (ø)
sbi/neural_nets/factory.py 93.24% <100.00%> (+11.31%) ⬆️
sbi/neural_nets/net_builders/vector_field_nets.py 94.03% <100.00%> (+0.72%) ⬆️
sbi/neural_nets/__init__.py 60.00% <0.00%> (+0.90%) ⬆️
sbi/neural_nets/estimators/score_estimator.py 91.89% <94.11%> (+0.35%) ⬆️
sbi/inference/trainers/vfpe/npse.py 84.61% <57.14%> (-5.87%) ⬇️

@manuelgloeckler manuelgloeckler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Great, makes sense to change this!

I think one can do a few changes (see comments), especially I would adapt the downstream code to now actually use the introduced dataclass instead of the kwargs.

Comment thread sbi/neural_nets/factory.py Resolved
Comment thread sbi/neural_nets/factory.py Resolved
Comment thread sbi/inference/trainers/vfpe/npse.py Resolved

@manuelgloeckler manuelgloeckler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Great!

Maybe it is already an issue, but I feel like a it would make sense to rewrite all the factories like this (i.e. replace the kwargs with dataclasses internally) so maybe makes sense to add an issue for that.

@janfb
janfb merged commit 7e31b4a into main Feb 24, 2026
9 checks passed
@janfb
janfb deleted the refactor-vectorfield-kwargs branch February 24, 2026 14:26
janfb pushed a commit that referenced this pull request Jul 31, 2026
flowmatching_nn was renamed to posterior_flow_nn and the function was deleted in
#1777. Nothing in the repo referenced the shim: the only tracked mentions were its own
two lines. With the embedding-net message also gone, the remaining __getattr__ body
just re-raised the AttributeError that Python already raises for a missing module
attribute, so the whole hook goes.

posterior_score_nn never needed an equivalent: it was introduced under that name in
#1015 and never renamed.
janfb added a commit that referenced this pull request Jul 31, 2026
…#1960)

* fix(npe): point trainers.npe SNPE_B alias at NPE_B

`sbi.inference.trainers.npe.SNPE_B` aliased `NPE_C` while
`sbi.inference.SNPE_B` aliased `NPE_B`. Both lines were written in the same
commit (b46c7c5); the mismatch was harmless while NPE-B raised
NotImplementedError, but NPE-B was implemented in #1471/#1691, so since v0.26.0
the submodule path silently returned an NPE-C trainer.

Add a test for the underlying invariant -- every legacy alias resolves to the
same class from either import path -- rather than for this one alias.

* fix(npe): re-enable invalid-x check for multi-round atomic NPE-C

The check guarding multi-round atomic NPE-C against invalid simulations
compared `type(self).__name__` against `SNPE_C`. Since the v0.23.0 rename
`SNPE_C` is only an alias of `NPE_C`, so the name is always `NPE_C` and the
branch has been unreachable. It was live and correct from #768 (Nov 2022) until
v0.23.0 (Aug 2024).

Restoring it means multi-round NPE-C again raises on NaN/Inf simulations:
`append_simulations` defaults to `exclude_invalid_x=False` for rounds > 0, which
is the arm of `nle_nre_apt_msg_on_invalid_x` that raises. Discarding invalid
simulations biases the atomic loss (Gloeckler et al. 2021), so raising is the
intended behavior. Users can pass `exclude_invalid_x=True` to get a warning and
have invalid rows dropped instead.

The exact name comparison excludes MNPE, which subclasses NPE_C. MNPE shipped in
v0.25.0, after the check was already dead, so it has never been subject to it;
widening to `isinstance` would be a separate decision.

Known limitation, unchanged here: `use_non_atomic_loss` is only recomputed in
`NPE_C.train()`, which runs after `append_simulations()`, so at the round-one
append it is still the initial `False` and the non-atomic MDN case also lands in
the strict branch.

Also add the missing separators in both invalid-x messages, which ran sentences
together ("0 Inf simulations.Multiround").

* remove deprecated sbi.utils.posterior_ensemble module

`NeuralPosteriorEnsemble` was renamed `EnsemblePosterior` and moved to
`sbi.inference.posteriors.ensemble_posterior` in v0.23.0, together with
`EnsemblePotential`. The forwarding module announced its own removal for v0.24,
three releases ago.

The shim also called `warnings.filterwarnings("default", ...)` at import time,
mutating the global warning filter as a side effect of an import.

Nothing depended on it: it was not exported from `sbi.utils`, and the only
consumer was the test asserting that it warns.

* remove deprecated MCMCPosterior arguments and init strategies

Five long-standing deprecations, three of which were already excluded from their
own `Literal` type annotations and so were only reachable by callers ignoring
type checks:

- `init_strategy_num_candidates` (v0.19.0), superseded by
  `init_strategy_parameters={"num_candidate_samples": ...}`
- `init_strategy="prior"` (v0.18.0), renamed to `"proposal"`
- `method="slice"` (v0.23.0), silently rewritten to `"slice_np"` since the
  Pyro-based slice sampler was dropped
- the `"hmc"`/`"nuts"` notice (v0.23.0), which only produced a better message
  immediately before `NotImplementedError`
- the SIR notice (v0.19.0), which was not a deprecated argument at all: it fired
  on every legitimate `init_strategy="sir"` call, telling users how to restore
  v0.18.0 behavior

Also give the init-strategy `NotImplementedError` a message, so an unsupported
strategy no longer raises with an empty traceback, and update the two docstrings
that still referred to `init_strategy_num_candidates`.

* remove deprecated bool flags for z-scoring

Boolean values for `z_score_x`/`z_score_theta` were deprecated in v0.18.0 in
favour of `"none"`, `"independent"` and `"structured"`. Passing a bool now raises
`ValueError` like any other invalid option, which the type annotations
(`Optional[Literal[...]]`) already implied.

The existing parser test both parametrized bools and guarded them with
`if z_x is bool`, comparing a value against a type, so the guard never ran and
its `match=` string never matched the real message. Replace it with an explicit
test that bools are rejected.

Unrelated: the boolean `z_score_theta` in `tarp.py` and
`sensitivity_analysis.py` is a different parameter and is untouched.

* remove check_warn_and_setstate and prepare_for_sbi

`check_warn_and_setstate` was a v0.16.0 helper for migrating pickled posteriors
across attribute renames. It had no call sites: `NeuralPosterior.__setstate__`
assigns the state dict directly, so the developer note pointing at it described
behavior that no longer existed.

`prepare_for_sbi` was deprecated in v0.23.0 in favour of calling `process_prior`
and `process_simulator` directly. It was not exported from `sbi.utils` and had no
callers in the package, tests or docs.

Also retarget the three docstrings that still described `prepare_for_sbi` as the
path users take.

* drop scipy.stats prior special case

Passing a `scipy.stats` object as a prior has raised `NotImplementedError` since
v0.23.0. Removing the branch lets such priors fall through to the custom-prior
path, which rejects them with an equally clear message:

    AttributeError: Prior needs method `.sample()`. Consider using a PyTorch
    distribution.

The exception type therefore changes from `NotImplementedError` to
`AttributeError`.

This also drops the imports of `scipy.stats._distn_infrastructure.rv_frozen` and
`scipy.stats._multivariate.multi_rv_frozen`, two private scipy paths that broke on
scipy upgrades, and widens `process_prior`'s annotation accordingly. scipy remains
a dependency, used elsewhere via its public API.

* remove misspelled conditonal_potential

The typo'd alias was kept for backwards compatibility when the function was
renamed in v0.19.0. It had no callers beyond its own re-export in
`sbi.analysis.__init__`; the docs reference only the correct spelling.

* remove legacy import stubs for snpe/snle/snre and embedding nets

The `sbi.inference.{snpe,snle,snre}` packages contained nothing but a `raise
ImportError` pointing at `sbi.inference.trainers.{npe,nle,nre}`, added for the
v0.23.0 rename. They now raise `ModuleNotFoundError` like any other missing
module. Their own examples recommended the deprecated class names, so they were
also steering users wrong.

In `sbi.neural_nets.__getattr__`, drop the v0.23.0 branch redirecting embedding
networks to `sbi.neural_nets.embedding_nets`; importing those names from
`sbi.neural_nets` still fails, just with the standard message. The six
`elif name == "<factory>": return <factory>` branches went with it: those names
are module-level imports, so normal attribute lookup always succeeded and
`__getattr__` was never reached. The `flowmatching_nn` branch is kept -- it is
from v0.26.0 and is the only one that was live.

* remove deprecated sbc_batch_size and NPE_A sample_with

`run_sbc(sbc_batch_size=...)` was deprecated in v0.23.0 in favour of
`num_workers`. The value was warned about and then discarded, so it never had an
effect. Its `**kwargs` catch-all goes with it: leaving it would turn the warning
into a silent no-op, which is what the deprecation existed to prevent. No caller
passed extra keywords.

`NPE_A_Posterior.sample(sample_with=...)` has raised since v0.18.0 and did nothing
else, so the parameter only existed to reject itself. `DirectPosterior.sample()`
has no such parameter, so the signatures now agree.

* review: type the custom-prior contract, and harden the alias test

Two findings from review.

`process_prior` was annotated `Union[Sequence[Distribution], Distribution, Any]`.
Once `Any` joins a union, no argument can fail the check, so the annotation was
equivalent to `Any` and silently dropped the contract. Add a `CustomPrior`
Protocol to `sbi/sbi_types.py`, next to the existing `SampleProposal`,
`AcceptRejectFn` and `Tracker` protocols, and use it. This states what
`process_prior` actually requires: `.sample()` and `.log_prob()`.

The alias-parity test guarded each module with `if hasattr(...)`, so the two
aliases that only `sbi.inference` defines, `SNL` and `SNRE`, asserted nothing and
passed silently. Drop those two from the parametrization and fail if no
sub-package defines the alias, so the test cannot become vacuous again.

* extend the invalid-x check to MNPE

Review found MNPE is exposed to the same bias as NPE-C. MNPE subclasses NPE_C, and
its `MixedDensityEstimator` is never a `MixtureDensityEstimator`, so
`use_non_atomic_loss` can never become True. Every multi-round MNPE run therefore
uses the atomic loss, whose normalizer is drawn from the training batch. MNPE is
in fact more exposed than NPE-C, which at least has the MoG path where the
correction is analytic.

Verified that multi-round MNPE runs and reports "atomic loss", so this is
reachable rather than theoretical.

Replace the class-name comparison with a check for the atomic loss method itself.
MNPE inherits it from NPE_C; NPE_A, NPE_B and NPE_PFN do not define it. The method
exists from instantiation, so unlike `_num_atoms` it carries no ordering problem.

Single-round behavior is unchanged for both trainers: round 0 uses the plain
log-prob loss, which filtering cannot bias, and the check is gated on
`current_round > 0`. Added a test for that boundary.

* document the round-one atomic assumption in append_simulations

Also drop the stale SNPE naming from that docstring.

* extend the invalid-x check to NPE-B

NPE-B normalizes its importance weights across the training batch
(`importance_weights /= importance_weights.sum()`), so discarding rows changes the
normalizer and the weights stop reflecting the proposal. Different mechanism from
NPE-C's atomic loss, same consequence, so it needs the same guard. Verified that
multi-round NPE-B reaches round 1 and is therefore affected.

With three of the four trainers exposed, the method-presence check no longer
captures the partition: NPE-B has no atomic loss method. Declare it instead, and
default to strict so a future variant is guarded unless it opts out. NPE-A opts
out, since it trains on the plain log-prob and corrects analytically after the
final round.

NPE-PFN is unaffected either way: it subclasses NeuralInference directly and
raises on multi-round.

Name the algorithm in the message after the trainer rather than hardcoding NPE-C.

* put the invalid-x exemption on NPE-A

Only NPE-A can safely discard invalid simulations in multi-round training, so it
carries the exemption instead of the other three declaring the guard. No base class
attribute: NPE-A sets `_per_row_multiround_loss` and `append_simulations` reads it
with a default.

Reusing `use_non_atomic_loss` for this would not work. `_get_start_idx` reads
`self.use_non_atomic_loss or hasattr(self, "_ran_final_round")`, so setting it on
NPE-A would also change which rounds' samples train the network.

Trim the tests to one parametrized case for the three guarded trainers plus one for
NPE-A. Drops the single-round test, which covered the pre-existing
`current_round > 0` gate rather than anything this branch changes.

* fix: restore last-round-only training for NPE-A

`_get_start_idx` checked `hasattr(self, "_ran_final_round")` to detect NPE-A. That
attribute was removed together with NPE-A's `final_round` machinery in #1724 and is
now assigned nowhere, so the branch was dead and multi-round NPE-A trained on all
accumulated rounds. Its own `train()` docstring says training uses samples from the
latest round, which is what the algorithm needs, so the code disagreed with the
documentation.

Use the same per-row-loss marker NPE-A already carries. Both arms of the condition
reach the same conclusion for different reasons: a current limitation for the
non-atomic loss, an algorithmic property for NPE-A.

Covered by `test_c2st_multi_round_snpe_on_linearGaussian[snpe_a]`, a two-round
accuracy test that passes.

* fix stale names and messages left by the renames

Four small leftovers, all from renames or deprecations this branch already cleans
up.

`sbi.inference.__all__` advertised the deprecated aliases `NLE`, `ABC` and `SMC`
while omitting the documented `MNLE` and `MNPE`, so `import *` handed out
deprecated names and hid canonical ones. It now mirrors the API reference. The
aliases stay importable.

`NPE_C.train()` printed "Using SNPE-C with ... loss" on every multi-round run,
using the pre-rename name and claiming SNPE-C even for MNPE. Name the trainer.

`append_simulations` hardcoded "Single-round NPE" in the lenient branch, which
NPE-A now reaches at rounds above zero. Derive the label once and use it in both
branches.

The NRE `loss_kwargs` warning was missing its `f` prefix, so it carried a literal
`{loss_kwargs.num_atoms}`, and had an unbalanced backtick. Note the message is
currently unreachable: NRE-A substitutes a default before delegating, and NRE-B,
NRE-C and BNRE do not expose `loss_kwargs` at all.

Note on `NLE_A`: there is no NLE-B or NLE-C, so the suffix is vestigial. `__all__`
follows the API reference here; making `NLE` canonical is a rename that belongs
with the alias deprecation work.

* export CustomPrior from sbi_types

The Protocol was defined but left out of `__all__`, unlike the three
Protocols beside it, so `import *` did not pick it up.

* fix: judge invalid simulations by the current proposal, not the last round

The guard read `self.use_non_atomic_loss`, which `NPE_C.train()` computes for the
round *before* the one being appended. That is wrong in both directions, and the
second one reintroduces the bias this check exists to prevent:

Round N with a MoG proposal sets the flag True. Round N+1 appends with a non-MoG
proposal, the guard reads the stale True and takes the lenient branch, so the
invalid rows are kept. `train()` then recomputes the flag as False and fits the
atomic loss to those rows. Reproduced with an MDN estimator and a BoxUniform
prior: the append does not raise, all 200 rows are stored, and training reports
the atomic loss before failing later with an unrelated message about NaN logits.

Replace the flag read with `_multiround_loss_is_per_row(proposal)`, evaluated
against the proposal being appended. The base returns False, NPE-C moves its
four-way MoG check there, and NPE-A returns True because it trains on the plain
log-prob for any proposal. NPE-B inherits False, MNPE inherits NPE-C.

This also removes the need for a separate NPE-A marker: the same method answers
`_get_start_idx`, since a per-row loss is exactly the case that cannot reuse
earlier rounds.

Tests: one for the stale-state sequence above, which needs two real `train()`
calls, and one asserting round 0 still only warns for NPE-B, NPE-C and MNPE.

* remove the unreachable NRE loss_kwargs warning

The message could not fire. `RatioEstimatorTrainer` is abstract, and every
concrete subclass sets `loss_kwargs` before delegating: NRE-A substitutes a
default, and NRE-B, NRE-C and BNRE do not expose the argument at all. So no public
entry point reaches it. It also carried a literal `{loss_kwargs.num_atoms}`,
missing its `f` prefix, which is how a broken message survived unnoticed.

Keep the default assignment as a defensive fallback, so a future subclass that
forgets still trains rather than raising a TypeError two lines later.

* fix multi-round docstring examples to pass the proposal

* finish the SNLE and SNRE renames in the invalid-x message

* update FAQ, tutorials, and prior check message for renames and removals

* reduce the single-round invalid-x test to one trainer

* drop the development history from the alias cross-path test docstring

* remove the flowmatching_nn import shim and the module __getattr__

flowmatching_nn was renamed to posterior_flow_nn and the function was deleted in
#1777. Nothing in the repo referenced the shim: the only tracked mentions were its own
two lines. With the embedding-net message also gone, the remaining __getattr__ body
just re-raised the AttributeError that Python already raises for a missing module
attribute, so the whole hook goes.

posterior_score_nn never needed an equivalent: it was introduced under that name in
#1015 and never renamed.

---------

Co-authored-by: Jan <[email protected]>
janfb added a commit that referenced this pull request Aug 3, 2026
* fix(npe): point trainers.npe SNPE_B alias at NPE_B

`sbi.inference.trainers.npe.SNPE_B` aliased `NPE_C` while
`sbi.inference.SNPE_B` aliased `NPE_B`. Both lines were written in the same
commit (b46c7c5); the mismatch was harmless while NPE-B raised
NotImplementedError, but NPE-B was implemented in #1471/#1691, so since v0.26.0
the submodule path silently returned an NPE-C trainer.

Add a test for the underlying invariant -- every legacy alias resolves to the
same class from either import path -- rather than for this one alias.

* fix(npe): re-enable invalid-x check for multi-round atomic NPE-C

The check guarding multi-round atomic NPE-C against invalid simulations
compared `type(self).__name__` against `SNPE_C`. Since the v0.23.0 rename
`SNPE_C` is only an alias of `NPE_C`, so the name is always `NPE_C` and the
branch has been unreachable. It was live and correct from #768 (Nov 2022) until
v0.23.0 (Aug 2024).

Restoring it means multi-round NPE-C again raises on NaN/Inf simulations:
`append_simulations` defaults to `exclude_invalid_x=False` for rounds > 0, which
is the arm of `nle_nre_apt_msg_on_invalid_x` that raises. Discarding invalid
simulations biases the atomic loss (Gloeckler et al. 2021), so raising is the
intended behavior. Users can pass `exclude_invalid_x=True` to get a warning and
have invalid rows dropped instead.

The exact name comparison excludes MNPE, which subclasses NPE_C. MNPE shipped in
v0.25.0, after the check was already dead, so it has never been subject to it;
widening to `isinstance` would be a separate decision.

Known limitation, unchanged here: `use_non_atomic_loss` is only recomputed in
`NPE_C.train()`, which runs after `append_simulations()`, so at the round-one
append it is still the initial `False` and the non-atomic MDN case also lands in
the strict branch.

Also add the missing separators in both invalid-x messages, which ran sentences
together ("0 Inf simulations.Multiround").

* remove deprecated sbi.utils.posterior_ensemble module

`NeuralPosteriorEnsemble` was renamed `EnsemblePosterior` and moved to
`sbi.inference.posteriors.ensemble_posterior` in v0.23.0, together with
`EnsemblePotential`. The forwarding module announced its own removal for v0.24,
three releases ago.

The shim also called `warnings.filterwarnings("default", ...)` at import time,
mutating the global warning filter as a side effect of an import.

Nothing depended on it: it was not exported from `sbi.utils`, and the only
consumer was the test asserting that it warns.

* remove deprecated MCMCPosterior arguments and init strategies

Five long-standing deprecations, three of which were already excluded from their
own `Literal` type annotations and so were only reachable by callers ignoring
type checks:

- `init_strategy_num_candidates` (v0.19.0), superseded by
  `init_strategy_parameters={"num_candidate_samples": ...}`
- `init_strategy="prior"` (v0.18.0), renamed to `"proposal"`
- `method="slice"` (v0.23.0), silently rewritten to `"slice_np"` since the
  Pyro-based slice sampler was dropped
- the `"hmc"`/`"nuts"` notice (v0.23.0), which only produced a better message
  immediately before `NotImplementedError`
- the SIR notice (v0.19.0), which was not a deprecated argument at all: it fired
  on every legitimate `init_strategy="sir"` call, telling users how to restore
  v0.18.0 behavior

Also give the init-strategy `NotImplementedError` a message, so an unsupported
strategy no longer raises with an empty traceback, and update the two docstrings
that still referred to `init_strategy_num_candidates`.

* remove deprecated bool flags for z-scoring

Boolean values for `z_score_x`/`z_score_theta` were deprecated in v0.18.0 in
favour of `"none"`, `"independent"` and `"structured"`. Passing a bool now raises
`ValueError` like any other invalid option, which the type annotations
(`Optional[Literal[...]]`) already implied.

The existing parser test both parametrized bools and guarded them with
`if z_x is bool`, comparing a value against a type, so the guard never ran and
its `match=` string never matched the real message. Replace it with an explicit
test that bools are rejected.

Unrelated: the boolean `z_score_theta` in `tarp.py` and
`sensitivity_analysis.py` is a different parameter and is untouched.

* remove check_warn_and_setstate and prepare_for_sbi

`check_warn_and_setstate` was a v0.16.0 helper for migrating pickled posteriors
across attribute renames. It had no call sites: `NeuralPosterior.__setstate__`
assigns the state dict directly, so the developer note pointing at it described
behavior that no longer existed.

`prepare_for_sbi` was deprecated in v0.23.0 in favour of calling `process_prior`
and `process_simulator` directly. It was not exported from `sbi.utils` and had no
callers in the package, tests or docs.

Also retarget the three docstrings that still described `prepare_for_sbi` as the
path users take.

* drop scipy.stats prior special case

Passing a `scipy.stats` object as a prior has raised `NotImplementedError` since
v0.23.0. Removing the branch lets such priors fall through to the custom-prior
path, which rejects them with an equally clear message:

    AttributeError: Prior needs method `.sample()`. Consider using a PyTorch
    distribution.

The exception type therefore changes from `NotImplementedError` to
`AttributeError`.

This also drops the imports of `scipy.stats._distn_infrastructure.rv_frozen` and
`scipy.stats._multivariate.multi_rv_frozen`, two private scipy paths that broke on
scipy upgrades, and widens `process_prior`'s annotation accordingly. scipy remains
a dependency, used elsewhere via its public API.

* remove misspelled conditonal_potential

The typo'd alias was kept for backwards compatibility when the function was
renamed in v0.19.0. It had no callers beyond its own re-export in
`sbi.analysis.__init__`; the docs reference only the correct spelling.

* remove legacy import stubs for snpe/snle/snre and embedding nets

The `sbi.inference.{snpe,snle,snre}` packages contained nothing but a `raise
ImportError` pointing at `sbi.inference.trainers.{npe,nle,nre}`, added for the
v0.23.0 rename. They now raise `ModuleNotFoundError` like any other missing
module. Their own examples recommended the deprecated class names, so they were
also steering users wrong.

In `sbi.neural_nets.__getattr__`, drop the v0.23.0 branch redirecting embedding
networks to `sbi.neural_nets.embedding_nets`; importing those names from
`sbi.neural_nets` still fails, just with the standard message. The six
`elif name == "<factory>": return <factory>` branches went with it: those names
are module-level imports, so normal attribute lookup always succeeded and
`__getattr__` was never reached. The `flowmatching_nn` branch is kept -- it is
from v0.26.0 and is the only one that was live.

* remove deprecated sbc_batch_size and NPE_A sample_with

`run_sbc(sbc_batch_size=...)` was deprecated in v0.23.0 in favour of
`num_workers`. The value was warned about and then discarded, so it never had an
effect. Its `**kwargs` catch-all goes with it: leaving it would turn the warning
into a silent no-op, which is what the deprecation existed to prevent. No caller
passed extra keywords.

`NPE_A_Posterior.sample(sample_with=...)` has raised since v0.18.0 and did nothing
else, so the parameter only existed to reject itself. `DirectPosterior.sample()`
has no such parameter, so the signatures now agree.

* review: type the custom-prior contract, and harden the alias test

Two findings from review.

`process_prior` was annotated `Union[Sequence[Distribution], Distribution, Any]`.
Once `Any` joins a union, no argument can fail the check, so the annotation was
equivalent to `Any` and silently dropped the contract. Add a `CustomPrior`
Protocol to `sbi/sbi_types.py`, next to the existing `SampleProposal`,
`AcceptRejectFn` and `Tracker` protocols, and use it. This states what
`process_prior` actually requires: `.sample()` and `.log_prob()`.

The alias-parity test guarded each module with `if hasattr(...)`, so the two
aliases that only `sbi.inference` defines, `SNL` and `SNRE`, asserted nothing and
passed silently. Drop those two from the parametrization and fail if no
sub-package defines the alias, so the test cannot become vacuous again.

* extend the invalid-x check to MNPE

Review found MNPE is exposed to the same bias as NPE-C. MNPE subclasses NPE_C, and
its `MixedDensityEstimator` is never a `MixtureDensityEstimator`, so
`use_non_atomic_loss` can never become True. Every multi-round MNPE run therefore
uses the atomic loss, whose normalizer is drawn from the training batch. MNPE is
in fact more exposed than NPE-C, which at least has the MoG path where the
correction is analytic.

Verified that multi-round MNPE runs and reports "atomic loss", so this is
reachable rather than theoretical.

Replace the class-name comparison with a check for the atomic loss method itself.
MNPE inherits it from NPE_C; NPE_A, NPE_B and NPE_PFN do not define it. The method
exists from instantiation, so unlike `_num_atoms` it carries no ordering problem.

Single-round behavior is unchanged for both trainers: round 0 uses the plain
log-prob loss, which filtering cannot bias, and the check is gated on
`current_round > 0`. Added a test for that boundary.

* document the round-one atomic assumption in append_simulations

Also drop the stale SNPE naming from that docstring.

* extend the invalid-x check to NPE-B

NPE-B normalizes its importance weights across the training batch
(`importance_weights /= importance_weights.sum()`), so discarding rows changes the
normalizer and the weights stop reflecting the proposal. Different mechanism from
NPE-C's atomic loss, same consequence, so it needs the same guard. Verified that
multi-round NPE-B reaches round 1 and is therefore affected.

With three of the four trainers exposed, the method-presence check no longer
captures the partition: NPE-B has no atomic loss method. Declare it instead, and
default to strict so a future variant is guarded unless it opts out. NPE-A opts
out, since it trains on the plain log-prob and corrects analytically after the
final round.

NPE-PFN is unaffected either way: it subclasses NeuralInference directly and
raises on multi-round.

Name the algorithm in the message after the trainer rather than hardcoding NPE-C.

* put the invalid-x exemption on NPE-A

Only NPE-A can safely discard invalid simulations in multi-round training, so it
carries the exemption instead of the other three declaring the guard. No base class
attribute: NPE-A sets `_per_row_multiround_loss` and `append_simulations` reads it
with a default.

Reusing `use_non_atomic_loss` for this would not work. `_get_start_idx` reads
`self.use_non_atomic_loss or hasattr(self, "_ran_final_round")`, so setting it on
NPE-A would also change which rounds' samples train the network.

Trim the tests to one parametrized case for the three guarded trainers plus one for
NPE-A. Drops the single-round test, which covered the pre-existing
`current_round > 0` gate rather than anything this branch changes.

* fix: restore last-round-only training for NPE-A

`_get_start_idx` checked `hasattr(self, "_ran_final_round")` to detect NPE-A. That
attribute was removed together with NPE-A's `final_round` machinery in #1724 and is
now assigned nowhere, so the branch was dead and multi-round NPE-A trained on all
accumulated rounds. Its own `train()` docstring says training uses samples from the
latest round, which is what the algorithm needs, so the code disagreed with the
documentation.

Use the same per-row-loss marker NPE-A already carries. Both arms of the condition
reach the same conclusion for different reasons: a current limitation for the
non-atomic loss, an algorithmic property for NPE-A.

Covered by `test_c2st_multi_round_snpe_on_linearGaussian[snpe_a]`, a two-round
accuracy test that passes.

* fix stale names and messages left by the renames

Four small leftovers, all from renames or deprecations this branch already cleans
up.

`sbi.inference.__all__` advertised the deprecated aliases `NLE`, `ABC` and `SMC`
while omitting the documented `MNLE` and `MNPE`, so `import *` handed out
deprecated names and hid canonical ones. It now mirrors the API reference. The
aliases stay importable.

`NPE_C.train()` printed "Using SNPE-C with ... loss" on every multi-round run,
using the pre-rename name and claiming SNPE-C even for MNPE. Name the trainer.

`append_simulations` hardcoded "Single-round NPE" in the lenient branch, which
NPE-A now reaches at rounds above zero. Derive the label once and use it in both
branches.

The NRE `loss_kwargs` warning was missing its `f` prefix, so it carried a literal
`{loss_kwargs.num_atoms}`, and had an unbalanced backtick. Note the message is
currently unreachable: NRE-A substitutes a default before delegating, and NRE-B,
NRE-C and BNRE do not expose `loss_kwargs` at all.

Note on `NLE_A`: there is no NLE-B or NLE-C, so the suffix is vestigial. `__all__`
follows the API reference here; making `NLE` canonical is a rename that belongs
with the alias deprecation work.

* export CustomPrior from sbi_types

The Protocol was defined but left out of `__all__`, unlike the three
Protocols beside it, so `import *` did not pick it up.

* fix: judge invalid simulations by the current proposal, not the last round

The guard read `self.use_non_atomic_loss`, which `NPE_C.train()` computes for the
round *before* the one being appended. That is wrong in both directions, and the
second one reintroduces the bias this check exists to prevent:

Round N with a MoG proposal sets the flag True. Round N+1 appends with a non-MoG
proposal, the guard reads the stale True and takes the lenient branch, so the
invalid rows are kept. `train()` then recomputes the flag as False and fits the
atomic loss to those rows. Reproduced with an MDN estimator and a BoxUniform
prior: the append does not raise, all 200 rows are stored, and training reports
the atomic loss before failing later with an unrelated message about NaN logits.

Replace the flag read with `_multiround_loss_is_per_row(proposal)`, evaluated
against the proposal being appended. The base returns False, NPE-C moves its
four-way MoG check there, and NPE-A returns True because it trains on the plain
log-prob for any proposal. NPE-B inherits False, MNPE inherits NPE-C.

This also removes the need for a separate NPE-A marker: the same method answers
`_get_start_idx`, since a per-row loss is exactly the case that cannot reuse
earlier rounds.

Tests: one for the stale-state sequence above, which needs two real `train()`
calls, and one asserting round 0 still only warns for NPE-B, NPE-C and MNPE.

* remove the unreachable NRE loss_kwargs warning

The message could not fire. `RatioEstimatorTrainer` is abstract, and every
concrete subclass sets `loss_kwargs` before delegating: NRE-A substitutes a
default, and NRE-B, NRE-C and BNRE do not expose the argument at all. So no public
entry point reaches it. It also carried a literal `{loss_kwargs.num_atoms}`,
missing its `f` prefix, which is how a broken message survived unnoticed.

Keep the default assignment as a defensive fallback, so a future subclass that
forgets still trains rather than raising a TypeError two lines later.

* fix multi-round docstring examples to pass the proposal

* finish the SNLE and SNRE renames in the invalid-x message

* update FAQ, tutorials, and prior check message for renames and removals

* reduce the single-round invalid-x test to one trainer

* warn on the legacy trainer aliases

The SNPE/SNLE/SNRE-era aliases have been silent since v0.23.0. A PEP 562
module __getattr__ now emits FutureWarning and names the replacement;
removal in v0.28.0. NPE, NLE and NRE stay silent: whether they become the
canonical names is a separate decision.

* warn on the deprecated vector-field builder wrappers

build_flow_matching_estimator and build_score_matching_estimator warn and
name build_vector_field_estimator, which is now exported from net_builders.
The factory calls the canonical builder directly, so the library does not
warn at itself.

* warn on sample_with in VectorFieldPosterior.sample

Documented as deprecated since v0.25.0, functional, and silent. Passing it
per call now emits FutureWarning; set it at construction instead.

* use canonical trainer names in infer() and the examples

infer() advertises 'npe', 'nle' and 'nre'; the legacy method strings still
resolve through the aliases and warn. The minimal example and the
SC_embedding docstrings use NPE_C.

* test the deprecation warnings, use canonical names in tests

Four new tests: every alias warns and resolves correctly, NPE/NLE/NRE stay
silent, the builder wrappers warn and delegate, sample_with warns. Tests
that are not about the aliases use canonical names; the two estimator test
files get local stand-ins for the wrappers, which pre-empts the v0.28.0
removal churn.

* attribute the infer() deprecation warning to the caller

Resolving the legacy method string through the module __getattr__ pointed
the FutureWarning at base.py instead of the user's script. infer() now
canonicalises the name itself and warns with the correct stacklevel. Found
in review. Also updates the last legacy alias in the FAQ examples.

* make the alias tests able to fail

test_deprecated_aliases_warn iterated _DEPRECATED_ALIASES, the dict the
implementation uses both to resolve and to compose the message. It could only prove
the implementation agrees with itself: injecting SNPE_B -> NPE_A passed cleanly. That
is the exact mis-dispatch test_legacy_aliases_agree_across_import_paths exists for.

Spell the mapping out as ground truth, add a completeness check so a missing or extra
entry fails, and match the 'Use ... instead' clause rather than the bare canonical
name: 14 of the pairs have the canonical name as a substring of the alias, so a bare
match succeeded against the first half of the message either way. The injected
mis-mapping now fails three tests.

Also silence the expected FutureWarnings on the cross-path test, which is about
agreement, not warning behaviour. It emitted 30 warnings per run and failed 10 of 13
cases under -W error::FutureWarning.

* drop the development history from the alias cross-path test docstring

* remove the flowmatching_nn import shim and the module __getattr__

flowmatching_nn was renamed to posterior_flow_nn and the function was deleted in
#1777. Nothing in the repo referenced the shim: the only tracked mentions were its own
two lines. With the embedding-net message also gone, the remaining __getattr__ body
just re-raised the AttributeError that Python already raises for a missing module
attribute, so the whole hook goes.

posterior_score_nn never needed an equivalent: it was introduced under that name in
#1015 and never renamed.

* trim the development history out of the alias test docstrings

* use the canonical trainer names in the last two test files

The alias deprecation made the test suite warn at itself.

* fix the always-false NRE guard on the multi-trial c2st test

`nre_method` is a class, so `isinstance` never matched and the KL-divergence
and MAP checks never ran. The block passes for NRE_A and BNRE.

* drop the duplicated alias table and the builder shims from the tests

The spelled-out alias table only caught divergence between two hand-written
copies, so it defended against nothing the code could get wrong. The tests now
read `_DEPRECATED_ALIASES` itself; the assertion that resolution matches the
canonical class still checks the implementation.

The local flow and score builders shadowed the deprecated public names. In
vf_estimator_test the call sites pass `estimator_type` instead. In
density_estimator_test the list they served was never referenced, so they and
the list are gone.

* fix: address review findings on the alias deprecation

- A module `__getattr__` is invisible to type checkers, so every alias resolved
  to `Any`. Users who stay on `SNPE_C` for the v0.27 cycle lost type checking
  and completion on it. `if TYPE_CHECKING:` blocks restore the types without
  changing what happens at run time.
- The trainer sub-packages define no `__all__`, so the new `import warnings`
  became a star-export and shadowed the caller's own `warnings`.
- `infer` accepts any trainer `sbi.inference` exports, but its docstring and
  its `NameError` both named only 'npe', 'nle' and 'nre'.

Tests: pin the alias set literally, since the other tests parametrize over the
dict itself and a dropped entry would shrink their collection instead of
failing. Add `AALR` and `CNRE` to the cross-path check. Pass `sde_type` to the
deprecated builders, so a shim that dropped `**kwargs` fails.

* fix: reject the ABC methods in `infer` with a message that helps

`infer` builds the trainer with `method_fun(prior=prior)`, then calls
`append_simulations().train()`. The ABC classes take the simulator at
construction and have no training step, so `infer(..., method='mcabc')` has
never worked: it raised `TypeError: MCABC.__init__() missing 1 required
positional argument: 'simulator'`.

The deprecation of `method='abc'` made this worse by advising `method='mcabc'`,
which fails the same way. `infer` now rejects the ABC methods before the
deprecation warning and shows how to call `MCABC`/`SMCABC` directly.

`MCABC.__call__` needs `eps` or `quantile`, `SMCABC.__call__` needs
`num_particles`, `num_initial_pop` and `epsilon_decay`, so the two classes get
their own example. One shared template would have sent the user from one
"missing required positional arguments" to the next.

* refactor: drop the TYPE_CHECKING blocks from the trainer sub-packages

These blocks gave static types to the deprecated aliases on the
`sbi.inference.trainers.npe` path and its two siblings. No document uses
that path: it occurs zero times in `docs/` and in `tutorials/`. The blocks
served an import that nobody was told about.

The block in `sbi/inference/__init__.py` stays. That path is the documented
one. Without the block, pyright resolves `from sbi.inference import SNPE`
to `Any`, and the `Any` then spreads to every call on the object.

The `__getattr__` functions stay in all four modules. They keep the
deprecation warning on each import path that worked before.

* refactor: move the ABC usage examples into the ABC docstrings

`infer` kept the example code for MCABC and SMCABC in a module-level dict.
This put ABC snippets in the neural trainer base module. It also kept them
away from the place where a user looks for them.

The examples are now `Examples:` sections on `MCABC.__call__` and
`SMCABC.__call__`. Neither class had one before.

The `ValueError` stays. It is the fix for the opaque `TypeError` that every
ABC spelling gave before. The message now names the class and points at its
docstring.

Also removes the inline comments about the underscored `warnings` import in
the three trainer sub-packages.

---------

Co-authored-by: Jan <[email protected]>
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