Skip to content

fix: four latent NPE and NRE bugs, and remove long-stale deprecations - #1960

Merged
janfb merged 27 commits into
mainfrom
fix/npe-c-invalid-x-and-stale-deprecations
Jul 31, 2026
Merged

janfb merged 27 commits into
mainfrom
fix/npe-c-invalid-x-and-stale-deprecations

Conversation

@janfb

@janfb janfb commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Removes deprecations that are three or more releases old, towards #1873. Four of them hid
bugs.

Bug fixes

  • sbi.inference.trainers.npe.SNPE_B aliased NPE_C. It now aliases NPE_B. A new test
    asserts that every legacy alias resolves to the same class from both import paths.
  • ⚠️ The invalid-simulation check for multi-round NPE (disallow invalid simulations from SNLE or SNRE #768) was dead since the v0.23.0
    rename: it compared the class name against SNPE_C. It is live again, and extended to
    NPE-B and MNPE, whose losses also normalise across the batch. Multi-round runs raise
    ValueError on NaN or Inf simulations again by default. Pass exclude_invalid_x=True
    to drop the invalid rows instead. NPE-A is exempt because its loss is per-row. The new
    _multiround_loss_is_per_row(proposal) makes this decision per trainer and judges the
    proposal being appended, not the previous round. Single-round behaviour is unchanged.
  • Multi-round NPE-A trained on all accumulated rounds. The last-round-only selection read
    _ran_final_round, an attribute Refactor MDN implementation: port MDN from pyknos, improve numerical stability #1724 removed. It now uses the same method as above.
  • An NRE warning about loss_kwargs could never fire, since every subclass supplies a
    value. Removed.

Removals

All deprecated in v0.23.0 or earlier:

  • sbi.utils.posterior_ensemble (NeuralPosteriorEnsemble, EnsemblePotential)
  • MCMCPosterior: init_strategy="prior", init_strategy_num_candidates,
    method="slice"/"hmc"/"nuts", and the SIR notice
  • bool values for z_score_x and z_score_theta
  • check_warn_and_setstate and prepare_for_sbi
  • scipy.stats objects as priors (also drops two private scipy imports)
  • conditonal_potential, the misspelled alias
  • the sbi.inference.snpe/snle/snre stubs and the dead branches in
    sbi.neural_nets.__getattr__
  • run_sbc(sbc_batch_size=...) and its **kwargs
  • sample_with in NPE_A_Posterior.sample()

num_freqs stays: it is only two releases old.

Also fixed

  • The NPE_A/B/C docstring examples now pass proposal=proposal. Without it, every round
    trains as round 0.
  • The NLE/NRE invalid-x messages say NLE/NRE, not SNLE/SNRE.
  • The NaN FAQ documents the restored error, the leakage FAQ and the multi-round tutorial
    show the renamed print, and the SBC tutorial passes use_batched_sampling (a typo the
    removed **kwargs used to swallow).

Validation

The fast suite, the slow NPE test files, ruff, and pyright sbi all pass.

Breaking changes, for the 0.27.0 release prep

Not applied to CHANGELOG.md here, to avoid a conflict with release-0.27.0. Copy this
block into the v0.27.0 section:

### ⚠️ Breaking Changes

- **Multi-round NPE-C again raises on invalid simulations by default.** The check from #768
  had been dead since v0.23.0, where it compared against the pre-rename class name `SNPE_C`.
  For rounds after the first, `append_simulations()` defaults `exclude_invalid_x` to `False`,
  so multi-round NPE-C now raises `ValueError` on NaN or Inf simulations. Pass
  `exclude_invalid_x=True` to drop the invalid rows and get a warning instead, which biases
  the atomic loss. `MNPE` and `NPE_B` are covered as well: MNPE is always atomic, and NPE-B
  normalises its importance weights across the batch. `NPE_A` is not, since its loss is
  per-row. Single-round runs are unaffected for every trainer.
- `sbi.inference.trainers.npe.SNPE_B` resolved to `NPE_C`. It now resolves to `NPE_B`, which
  matches `sbi.inference.SNPE_B`.
- **`from sbi.inference import *` no longer provides `NLE`, `ABC` or `SMC`.** `__all__` now
  lists the canonical names the API reference documents, and adds the missing `MNLE` and
  `MNPE`. All three aliases remain importable by name; only the star import changes.
- **Multi-round NPE-A again trains only on the latest round.** The check that selected this
  used `_ran_final_round`, an attribute removed in #1724, so multi-round NPE-A had been
  training on all accumulated rounds instead, contrary to `NPE_A.train()`'s documented
  behaviour.
- Removed these long-deprecated items: `sbi.utils.posterior_ensemble` with
  `NeuralPosteriorEnsemble` and `EnsemblePotential`; bool values for `z_score_x` and
  `z_score_theta`; `MCMCPosterior(init_strategy="prior")`; `init_strategy_num_candidates`;
  `method="slice"`; the `"hmc"` and `"nuts"` method names; `conditonal_potential`;
  `check_warn_and_setstate`; `prepare_for_sbi`; `run_sbc(sbc_batch_size=...)`; `scipy.stats`
  objects as priors; `sample_with` in `NPE_A_Posterior.sample()`; and the import stubs in
  `sbi.inference.snpe`, `sbi.inference.snle`, `sbi.inference.snre` and `sbi.neural_nets`.

Claude Code helped with the audit and the removals.

Refs #1873

janfb added 24 commits July 30, 2026 12:55
`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.
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").
`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.
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`.
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.
`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.
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.
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.
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.
`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.
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.
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.
Also drop the stale SNPE naming from that docstring.
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.
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.
`_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.
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.
The Protocol was defined but left out of `__all__`, unlike the three
Protocols beside it, so `import *` did not pick it up.
…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.
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.
@codecov

codecov Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 88.77%. Comparing base (33dd963) to head (08447df).
⚠️ Report is 1 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/inference/posteriors/mcmc_posterior.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1960      +/-   ##
==========================================
+ Coverage   88.59%   88.77%   +0.18%     
==========================================
  Files         143      143              
  Lines       13585    13538      -47     
==========================================
- Hits        12035    12019      -16     
+ Misses       1550     1519      -31     
Flag Coverage Δ
fast 83.27% <95.65%> (?)

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

Files with missing lines Coverage Δ
sbi/analysis/__init__.py 100.00% <ø> (ø)
sbi/analysis/conditional_density.py 93.44% <ø> (+2.67%) ⬆️
sbi/diagnostics/sbc.py 89.41% <ø> (+0.90%) ⬆️
sbi/inference/__init__.py 100.00% <100.00%> (ø)
sbi/inference/posteriors/base_posterior.py 85.18% <ø> (ø)
sbi/inference/posteriors/npe_a_posterior.py 56.97% <ø> (+0.15%) ⬆️
sbi/inference/posteriors/posterior_parameters.py 83.33% <ø> (ø)
sbi/inference/trainers/nle/nle_base.py 96.87% <ø> (ø)
sbi/inference/trainers/npe/__init__.py 100.00% <100.00%> (ø)
sbi/inference/trainers/npe/npe_a.py 79.24% <100.00%> (+0.26%) ⬆️
... and 10 more

... and 3 files with indirect coverage changes

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

self-review, will be fixed locally.

Comment thread sbi/neural_nets/__init__.py Resolved
Comment thread tests/base_test.py Resolved
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
janfb merged commit 3a1e2b7 into main Jul 31, 2026
20 checks passed
@janfb
janfb deleted the fix/npe-c-invalid-x-and-stale-deprecations branch July 31, 2026 10:37
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.

1 participant