Repository navigation
fix: four latent NPE and NRE bugs, and remove long-stale deprecations - #1960
Merged
Merged
Conversation
`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 Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more.
|
This was referenced Jul 30, 2026
janfb
commented
Jul 31, 2026
janfb
left a comment
Contributor
Author
There was a problem hiding this comment.
self-review, will be fixed locally.
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.
5 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Removes deprecations that are three or more releases old, towards #1873. Four of them hid
bugs.
Bug fixes
sbi.inference.trainers.npe.SNPE_BaliasedNPE_C. It now aliasesNPE_B. A new testasserts that every legacy alias resolves to the same class from both import paths.
rename: it compared the class name against
SNPE_C. It is live again, and extended toNPE-B and MNPE, whose losses also normalise across the batch. Multi-round runs raise
ValueErroron NaN or Inf simulations again by default. Passexclude_invalid_x=Trueto 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 theproposal being appended, not the previous round. Single-round behaviour is unchanged.
_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.loss_kwargscould never fire, since every subclass supplies avalue. 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 noticez_score_xandz_score_thetacheck_warn_and_setstateandprepare_for_sbiscipy.statsobjects as priors (also drops two private scipy imports)conditonal_potential, the misspelled aliassbi.inference.snpe/snle/snrestubs and the dead branches insbi.neural_nets.__getattr__run_sbc(sbc_batch_size=...)and its**kwargssample_withinNPE_A_Posterior.sample()num_freqsstays: it is only two releases old.Also fixed
proposal=proposal. Without it, every roundtrains as round 0.
NLE/NRE, notSNLE/SNRE.show the renamed print, and the SBC tutorial passes
use_batched_sampling(a typo theremoved
**kwargsused to swallow).Validation
The fast suite, the slow NPE test files,
ruff, andpyright sbiall pass.Breaking changes, for the 0.27.0 release prep
Not applied to
CHANGELOG.mdhere, to avoid a conflict withrelease-0.27.0. Copy thisblock into the
v0.27.0section:Claude Code helped with the audit and the removals.
Refs #1873