Skip to content

deprecation: attach observations to potentials only with bind() - #2248

Merged
janfb merged 2 commits into
mainfrom
deprecate-potential-x-o
Nov 30, 2026
Merged

janfb merged 2 commits into
mainfrom
deprecate-potential-x-o

Conversation

@janfb

@janfb janfb commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Part of #1994. The removal in sbi 0.29 follows in a second PR.

Summary

A potential gets its observation in two ways today: x_o in its constructor or factory, or bind(x_o). A posterior also takes its default x from a bound potential. This PR deprecates both, so that bind() is the only way to attach an observation and x flows one way, from the posterior to the potential. Both go in sbi 0.29, together with set_x(), which already warns.

# before
potential_fn, transform = likelihood_estimator_based_potential(estimator, prior, x_o)
posterior = MCMCPosterior(potential_fn, proposal=prior, theta_transform=transform)
samples = posterior.sample((1000,))

# after, with a posterior
potential_fn, transform = likelihood_estimator_based_potential(estimator, prior)
posterior = MCMCPosterior(potential_fn, proposal=prior, theta_transform=transform)
samples = posterior.sample((1000,), x=x_o)  # or posterior.set_default_x(x_o)

# after, when you evaluate the potential yourself
log_potential = potential_fn.bind(x_o)(theta)
Call Warns
x_o in any potential constructor or *_estimator_based_potential, also x_o=None "Passing x_o to a potential's constructor is deprecated and will be removed in sbi 0.29. …"
A posterior that uses a default x it took from a bound potential "This posterior has no default x, so it uses the x bound to its potential (by bind() or by an earlier posterior call). …"

Both warnings are FutureWarnings and point to the user's line. The second one fires only when the posterior uses that x, so building a posterior from a bound potential and then calling set_default_x() stays silent. In 0.29 the arguments after prior become keyword-only, so an old positional x_o fails with a TypeError instead of shifting into the next argument. That is why an explicit x_o=None warns too, and why the warning asks for keyword arguments. Until 0.29 the behaviour does not change: a passed x_o still binds, and the posterior still uses it as its default x.

A custom subclass of BasePotential drops x_o from its __init__ and from super().__init__(). If it derives state from x_o, it does so where it reads self.x_o. The BinomialGammaPotential of the decision-making tutorial shows how.

Also in this PR:

  • sbi itself no longer passes x_o, so users see only warnings about their own code.
  • The four "Please reinitialize the potential or manually set self._x_o" checks go. An unbound potential now raises one message: "No observed data is available. Use potential_fn.bind(x_o)." The vector-field potential raised an AttributeError before.
  • The set_x() warnings name sbi 0.29.
  • CustomPotentialWrapper uses the base bind().
  • _stacklevel_to_caller() moves from the trainers to sbi/utils/sbiutils.py, so that potentials and posteriors can use it.
  • The sampler-interface how-to says when to use bind() and when set_default_x(). The tutorials and tests use the new form.

Evidence

  • test_x_o_at_construction_warns_and_binds: constructor x_o warns and still binds.
  • test_factory_x_o_warns_also_when_none: a factory warns on an explicit None.
  • test_posterior_warns_when_it_uses_x_of_bound_potential: building the posterior and passing x is silent; using the x of the bound potential warns.
  • The changed test files pass with both warnings turned into errors, so no sbi code path triggers them.

Merge Danger

Door: two-way. The PR adds warnings and changes no results.

Blast Radius: small. Users who pass x_o to a potential see a FutureWarning. Code that runs with warnings as errors fails until it moves to bind().

Passing `x_o` to a potential constructor or to a `*_estimator_based_potential` factory now warns with a FutureWarning, also as `None`. The factories pass `x_o` through, so `BasePotential.__init__` is the one place that warns. The warning asks to pass the arguments after `prior` by keyword: sbi 0.29 replaces `x_o` with a keyword-only marker, so that old positional calls fail instead of shifting into `enable_transform` or `device`. The passed `x_o` still binds until then.

A posterior that uses a default `x` it took from a bound potential warns that this stops in 0.29. The warning fires on use, not on construction, because posteriors write their bound potential back to `potential_fn` and building a new posterior from it is fine. The ensemble and VI posteriors read `default_x` once per call, so each use warns once.

sbi no longer passes `x_o` internally. The duplicate "reinitialize the potential" checks go, so an unbound potential raises the one `bind()` message; the vector-field potential raised an `AttributeError` before. `ConditionedPotential.return_x_o()` delegates instead of reading `_x_o`. The `set_x()` warnings name sbi 0.29. `_stacklevel_to_caller()` moves to `sbi.utils.sbiutils` so potentials and posteriors attribute the warnings to the user's line.

Tests, the sampler-interface how-to, the conditional-distributions and training-interface tutorials and the decision-making example use `bind()` or `set_default_x()`.

Part of #1994.
@janfb
janfb requested a review from dgedon November 27, 2026 15:40
@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Potential constructors and factories now deprecate x_o in favor of bind(x_o). Posterior observation handling and internal callers use the updated binding flow. Tutorials, examples, and tests reflect these changes.

Changes: Observation Binding

Layer / File(s) Summary
Potential API and binding contract
sbi/inference/potentials/*, sbi/inference/posteriors/ensemble_posterior.py, tests/potential_test.py, tests/compose_standardization_test.py, tests/test_utils.py
Potential constructors and factories use a sentinel default for deprecated x_o arguments. bind() behavior and deprecation warnings are updated. Tests cover binding and explicit x_o warnings.
Posterior observation resolution
sbi/inference/posteriors/base_posterior.py, sbi/inference/posteriors/ensemble_posterior.py, sbi/inference/posteriors/vi_posterior.py, sbi/utils/*, sbi/inference/trainers/base.py, sbi/inference/trainers/marginal/marginal_base.py, tests/potential_test.py, tests/user_input_checks_test.py
Posteriors track when their default observation comes from a potential and warn when that default is accessed. Ensemble observation checks, VI observation resolution, and warning stack-level selection are updated.
Internal potential callers and test migration
sbi/inference/posteriors/*, sbi/inference/trainers/*, tests/linearGaussian_*, tests/inference_on_device_test.py, tests/posterior_*, tests/score_samplers_test.py, tests/vi_test.py, tests/user_input_checks_test.py, tests/potential_test.py
Internal factory calls omit x_o=None. Tests provide observations through posterior methods or bind them to potentials.
BinomialGamma observation and scaling
docs/tutorials/Example_01_DecisionMakingModel.ipynb, docs/tutorials/example_01_utils.py, tests/mnle_test.py
BinomialGammaPotential no longer accepts constructor observations. Tensor scaling validation and reshaping occur in iid_likelihood. Examples and tests supply observations through sampling or bind().
Observation-binding documentation
docs/advanced_tutorials/*, docs/how_to_guide/09_sampler_interface.ipynb
Tutorials omit observations from potential factory calls. The sampler guide describes bind(), posterior observation methods, and removal of deprecated arguments in sbi 0.29.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Other

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant NeuralPosterior
  participant Potential
  Caller->>NeuralPosterior: Set or pass observation
  NeuralPosterior->>Potential: Bind observation for evaluation
  Potential-->>NeuralPosterior: Return potential evaluation
Loading

Possibly related issues

  • sbi-dev/sbi#1994: Proposes deprecating x_o in potential constructors and using bind(); this change updates those APIs and their documentation.

Possibly related PRs

  • sbi-dev/sbi#2130: Both changes update how posterior code binds observations into potentials.
  • sbi-dev/sbi#2140: Both changes update observation handling across ensemble potentials, VI, and posterior evaluation.

Suggested reviewers: aniketpandey05, michaeldeistler, ashwini8686, manuelgloeckler

Merge Risk: Minimal · up to 88ea4

This change deprecates passing x_o to potential constructors and deprecates the posterior fallback to the potential's bound observation. Behavior is unchanged until sbi 0.29, and the new warnings tell users how to migrate. No merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "deprecation: attach observations to potentials only with bind()" matches the main change. The PR deprecates passing x_o to potential constructors and factories, and makes bind(x_o) the only…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description states the purpose clearly: it deprecates passing x_o to potential constructors and factories, and deprecates a posterior's fallback to a potential's bound x, so bind() becomes t…
Full details: Title check

Explanation

The title "deprecation: attach observations to potentials only with bind()" matches the main change. The PR deprecates passing x_o to potential constructors and factories, and makes bind(x_o) the only way to attach an observation. The title is specific and concise, and it follows a conventional commit style.

Full details: Description check

Explanation

The description states the purpose clearly: it deprecates passing x_o to potential constructors and factories, and deprecates a posterior's fallback to a potential's bound x, so bind() becomes the only way to attach an observation. It gives before/after usage examples, a table of the new warnings, the removal timeline for sbi 0.29, a list of related changes, and test evidence. It also includes a merge-risk section (two-way door, small blast radius). It links the parent issue (#1994) through 'Part of #1994', but it does not use the template's 'Does this close any issues?' heading. The template's 'Anything else we should know?' section is also absent, and the checklist items (contributing guide, pytest, pre-commit, pyright, Google-style docstrings, slow-test timing, AI-assistance disclosure) are not addressed. These are non-critical administrative items, but the template structure is not followed.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3e994b1a-1e4d-44c1-9a82-1848128d6ba7
Commits

Reviewing files that changed from the base of the PR and between 305635b and 88ea4b4.

Files selected for processing: 3

  • sbi/inference/posteriors/base_posterior.py
  • tests/inference_on_device_test.py
  • tests/potential_test.py
Files skipped from review as they are similar to previous changes: 1

  • sbi/inference/posteriors/base_posterior.py

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.73684% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.81%. Comparing base (c74f0aa) to head (88ea4b4).
⚠️ Report is 3 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/inference/potentials/vector_field_potential.py 83.33% 1 Missing ⚠️
sbi/utils/conditional_density_utils.py 50.00% 1 Missing ⚠️
sbi/utils/sbiutils.py 92.30% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2248      +/-   ##
==========================================
+ Coverage   88.88%   90.81%   +1.93%     
==========================================
  Files         149      149              
  Lines       16574    17481     +907     
==========================================
+ Hits        14731    15876    +1145     
+ Misses       1843     1605     -238     
Flag Coverage Δ
fast 89.14% <94.73%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/posteriors/base_posterior.py 96.48% <100.00%> (+2.09%) ⬆️
sbi/inference/posteriors/direct_posterior.py 99.41% <ø> (+1.39%) ⬆️
sbi/inference/posteriors/ensemble_posterior.py 96.50% <100.00%> (+4.50%) ⬆️
sbi/inference/posteriors/vector_field_posterior.py 92.91% <ø> (-0.26%) ⬇️
sbi/inference/posteriors/vi_posterior.py 88.95% <100.00%> (+1.22%) ⬆️
sbi/inference/potentials/base_potential.py 89.01% <100.00%> (+4.12%) ⬆️
...inference/potentials/likelihood_based_potential.py 91.80% <100.00%> (ø)
.../inference/potentials/posterior_based_potential.py 90.78% <ø> (+1.04%) ⬆️
sbi/inference/potentials/ratio_based_potential.py 98.14% <100.00%> (ø)
sbi/inference/trainers/base.py 94.76% <ø> (+1.46%) ⬆️
... and 9 more

... and 55 files with indirect coverage changes

@dgedon dgedon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM, accepted with some small optional edits inline below

Comment thread tests/potential_test.py
assert torch.isfinite(constructed(zeros(1, 2))).all()


def test_posterior_warns_when_it_uses_x_of_bound_potential():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could we also test that set_default_x() silences this warning? The same goes for EnsemblePosterior.set_default_x() and the VIPosterior.set_q() copy.

@property
def default_x(self) -> Optional[Tensor]:
"""Return default x used by `.sample(), .log_prob` as conditioning context."""
if self._x_from_potential:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reading default_x can now warn, so the code reads it once per call. Could we add a short comment here so later edits keep that?

"""Return default x used by `.sample(), .log_prob` as conditioning context."""
if self._x_from_potential:
warn(
"This posterior uses the `x` bound to its potential as its default "

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The second sentence of this warning is hard to parse. Could we simplify it?

@dgedon

dgedon commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

tests/inference_on_device_test.py:762 still passes x_o to EnsemblePotential. Since this test runs only on GPU, CI misses the warning. Could it use .bind(x_o)?

The posterior warning now says in two sentences that the posterior falls back to the `x` bound to its potential and that sbi 0.29 removes this fallback. A comment on `default_x` notes that reading it can warn, so callers read it once per call.

The GPU-only device test passed `x_o` to `EnsemblePotential`, which CI does not run; it binds now. The posterior warning test also checks that `set_default_x()` silences the warning and that a VI copy keeps its source's state.
@janfb

janfb commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review! All four points are in now. The warning reads: "This posterior has no default x, so it uses the x bound to its potential (by bind() or by an earlier posterior call). sbi 0.29 removes this fallback: call set_default_x(x) or pass x to sample()."

The ensemble needs no test of its own: its set_default_x() calls the base method that clears the fallback.

@janfb
janfb merged commit 1c3d53d into main Nov 30, 2026
21 checks passed
@janfb
janfb deleted the deprecate-potential-x-o branch November 30, 2026 12:09
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