Skip to content

first attempt to remove potential.to and let the poeterior handle it - #1949

Closed
Jocho-Smith wants to merge 8 commits into
sbi-dev:gsoc-2026from
Jocho-Smith:remove-potential-to-method
Closed

Jocho-Smith wants to merge 8 commits into
sbi-dev:gsoc-2026from
Jocho-Smith:remove-potential-to-method

Conversation

@Jocho-Smith

Copy link
Copy Markdown
Contributor

first attempt to remove potential.to and let the poeterior handle it.

The idea for the usage is that there are 2 ways of setting this up:

Option 1: Move components before creating potential:

estimator.to(device)
prior = prior.to(device)
x = x.to(device)
potential = SomePotential)estimator, prior).bind(x)

Option 2: Use posterior.to(device)

posterior = inference.build_posterior()
posterior.to(device)

Note: the _move_estimator_to_device seems a bit unintuitive at first, b/c its definition inside BasePotential just returns self, however for the other potentials there is runs the estimator removal. This feels a bit off, however I can't think of any other way of doing this

@Jocho-Smith

Jocho-Smith commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor Author

(see update below) Note also that I added this optional _check_on_device inside potential calls, to check if user has set the devices correctly. Maybe this it not desired though.

Update: This actually caused this error:

FAILED tests/linearGaussian_vector_field_test.py::test_c2st_vector_field_on_linearGaussian[vp-3-gaussian-sample_with2] - AssertionError: D-KL=tensor([0.3336]) is more than 2 stds above the average performance.
assert tensor([0.3336]) < 0.25

So I removed it again!

… this test failed - there it was b/c a new potential was created every time forgetting about the params from before. Maybe this is the fix here as well
…ast time this test failed - there it was b/c a new potential was created every time forgetting about the params from before. Maybe this is the fix here as well"

This reverts commit d3010de.
@codecov

codecov Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 40.32258% with 37 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.82%. Comparing base (587f922) to head (e13cfd9).
⚠️ Report is 40 commits behind head on gsoc-2026.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/inference/posteriors/ensemble_posterior.py 11.11% 8 Missing ⚠️
sbi/inference/posteriors/vi_posterior.py 41.66% 7 Missing ⚠️
sbi/inference/posteriors/importance_posterior.py 14.28% 6 Missing ⚠️
sbi/inference/posteriors/mcmc_posterior.py 14.28% 6 Missing ⚠️
sbi/inference/posteriors/rejection_posterior.py 14.28% 6 Missing ⚠️
sbi/inference/potentials/vector_field_potential.py 33.33% 2 Missing ⚠️
sbi/inference/posteriors/direct_posterior.py 50.00% 1 Missing ⚠️
sbi/inference/posteriors/vector_field_posterior.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##           gsoc-2026    #1949      +/-   ##
=============================================
- Coverage      87.99%   87.82%   -0.18%     
=============================================
  Files            144      144              
  Lines          13499    13745     +246     
=============================================
+ Hits           11879    12071     +192     
- Misses          1620     1674      +54     
Flag Coverage Δ
fast 81.55% <40.32%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/potentials/base_potential.py 89.58% <100.00%> (-3.28%) ⬇️
...inference/potentials/likelihood_based_potential.py 82.65% <100.00%> (+0.54%) ⬆️
.../inference/potentials/posterior_based_potential.py 96.55% <100.00%> (+0.18%) ⬆️
sbi/inference/potentials/ratio_based_potential.py 100.00% <100.00%> (ø)
sbi/samplers/vi/vi_divergence_optimizers.py 84.93% <100.00%> (-0.09%) ⬇️
sbi/inference/posteriors/direct_posterior.py 84.48% <50.00%> (+1.57%) ⬆️
sbi/inference/posteriors/vector_field_posterior.py 78.76% <50.00%> (+0.53%) ⬆️
sbi/inference/potentials/vector_field_potential.py 94.35% <33.33%> (+3.37%) ⬆️
sbi/inference/posteriors/importance_posterior.py 72.28% <14.28%> (-4.34%) ⬇️
sbi/inference/posteriors/mcmc_posterior.py 81.94% <14.28%> (-1.88%) ⬇️
... and 3 more

... and 4 files with indirect coverage changes

@Jocho-Smith Jocho-Smith mentioned this pull request Jul 23, 2026
11 tasks done
@Jocho-Smith

Copy link
Copy Markdown
Contributor Author

ChatGPT also suggested another way of solving this. Maybe this is also an interesting solution.

see here

Migration: Remove .to() from Potentials

Overview

Remove the .to(device) method from potential classes (BasePotential and subclasses) and migrate device handling to posteriors. This is part of the broader API redesign to remove hidden mutable state.

Problem

  • BasePotential.to() mixes device handling with observation state (_x_o)
  • Posteriors already have .to() that orchestrates full migration
  • Calling potential_fn.to(device) directly is redundant when users have access to posterior.to(device)

Scope

  • Remove .to() from all potential classes in sbi/inference/potentials/
  • Update all internal call sites that call .to() on potential functions

Step 1: Add Deprecation Warning to BasePotential.to()

File: sbi/inference/potentials/base_potential.py

Add deprecation warning that raises after a grace period:

def to(self, device: Union[str, torch.device]) -> "BasePotential":
    """Moved to posterior.to() for proper state migration."""
    import warnings
    warnings.warn(
        "potential.to(device) is deprecated. Use posterior.to(device) instead.",
        FutureWarning,
        stacklevel=2,
    )
    raise NotImplementedError(
        "Device handling moved to posterior. Use posterior.to(device) instead."
    )

Rationale: Users calling .to() directly on potentials get a clear error message pointing them to use posterior.to().


Step 2: Update Subclass .to() Methods

Each subclass overrides .to() - update them to call parent (which will raise):

File Class Current Lines Action
likelihood_based_potential.py LikelihoodBasedPotential ~93-94 Remove override or call parent
ratio_based_potential.py RatioBasedPotential ~81-82 Remove override or call parent
posterior_based_potential.py PosteriorBasedPotential ~99-100 Remove override or call parent
vector_field_potential.py VectorFieldBasedPotential ~91-95 Remove override or call parent
vector_field_adaptor.py VectorFieldAdaptor Multiple Remove overrides

Action for each: Replace with:

def to(self, device: Union[str, torch.device]) -> "ClassName":
    """Device handling moved to posterior.to()."""
    import warnings
    warnings.warn(
        "potential.to(device) is deprecated. Use posterior.to(device) instead.",
        FutureWarning,
        stacklevel=2,
    )
    raise NotImplementedError(
        "Device handling moved to posterior. Use posterior.to(device) instead."
    )

Or simply inherit the parent's implementation if the parent raises.


Step 3: Update Internal Call Sites

Remove or refactor the 7 internal call sites that call .to() on potential functions:

3.1 mcmc_posterior.py (line 172)

# BEFORE
self.potential_fn.to(device)  # type: ignore
self.proposal.to(device)

# AFTER
# Remove potential_fn.to() - posterior.to() will handle device via new mechanism
self.proposal.to(device)

Note: Need to ensure posterior.to() properly moves the neural estimator. See Step 4.

3.2 vi_posterior.py (lines 159, 227, 1112)

# Line 159 - in to() method
# BEFORE
self.potential_fn.to(device)

# AFTER
# Remove - handled by posterior.to()

# Line 227 - in to() method  
# BEFORE
self.potential_fn.to(device)

# AFTER
# Remove - handled by posterior.to()

# Line 1112 - in _build_variational_posterior()
# BEFORE
self.potential_fn.to(self._device)

# AFTER
# Remove - potential already has x bound, device handled elsewhere

3.3 rejection_posterior.py (line 85)

# BEFORE
self.potential_fn.to(device)  # type: ignore
self.proposal.to(device)

# AFTER
# Remove potential_fn.to()
self.proposal.to(device)

3.4 importance_posterior.py (line 91)

# BEFORE
self.potential_fn.to(device)  # type: ignore
self.proposal.to(device)

# AFTER
# Remove potential_fn.to()
self.proposal.to(device)

3.5 vi_divergence_optimizers.py (line 176)

# BEFORE
self.potential_fn.to(self.device)

# AFTER
# This is in VI optimizer, not posterior. Need alternative:
# Either: Move estimator directly before creating potential
# Or: Ensure potential receives already-moved estimator

Note: The VI optimizer case is different - it's not inside a posterior.to() call. Options:

  1. Move estimator/prior to device before constructing the potential
  2. Create a helper that moves all components of a potential

Step 4: Ensure Posteriors Properly Handle Device Migration

After removing potential_fn.to(), the posterior's .to() must handle moving all components:

Current Pattern in posterior.to()

def to(self, device):
    self.device = device
    self.potential_fn.to(device)  # Will now raise!
    # ... other moves

New Pattern

The posterior should move components directly:

def to(self, device):
    self.device = device
    
    # Move prior
    if self.prior is not None:
        self.prior = move_distribution_to_device(self.prior, device)
    
    # Move neural estimator inside potential (access via getattr)
    if hasattr(self.potential_fn, 'likelihood_estimator'):
        self.potential_fn.likelihood_estimator.to(device)
    elif hasattr(self.potential_fn, 'posterior_estimator'):
        self.potential_fn.posterior_estimator.to(device)
    elif hasattr(self.potential_fn, 'ratio_estimator'):
        self.potential_fn.ratio_estimator.to(device)
    elif hasattr(self.potential_fn, 'vector_field_estimator'):
        self.potential_fn.vector_field_estimator.to(device)
    # ... etc for other potential types
    
    # Move x_o if present
    if hasattr(self.potential_fn, '_x_o') and self.potential_fn._x_o is not None:
        self.potential_fn._x_o = self.potential_fn._x_o.to(device)
    
    # Move other state (proposal, etc.)
    # ...

Alternative: Create a utility function move_potential_to_device(potential, device) that handles all potential types.


Step 5: Handle Custom Potentials

For CustomPotentialWrapper, users may pass custom callables. Device handling becomes user's responsibility:

# In CustomPotentialWrapper.to()
def to(self, device):
    import warnings
    warnings.warn(
        "CustomPotentialWrapper.to(device) is deprecated. "
        "Ensure your custom potential handles device placement.",
        FutureWarning,
    )
    raise NotImplementedError(
        "Device handling for custom potentials is user's responsibility. "
        "Move tensors before passing to potential."
    )

Step 6: Test Verification

After implementation, verify:

  1. No direct potential.to() calls remain:

    grep -r "potential_fn\.to\|potential\.to" sbi/ --include="*.py"
  2. All posterior.to() work correctly - run existing tests:

    pytest tests/ -k "test_posterior_to"  # or similar
  3. User code gets helpful error:

    potential = LikelihoodBasedPotential(...)
    potential.to("cuda")  # Should raise NotImplementedError with helpful message

Backward Compatibility Timeline

Phase Action
v0.23 Add FutureWarning, raise NotImplementedError
v0.24 Remove .to() entirely from potentials
v1.0 Remove all deprecation code

Files to Modify

Potentials (remove/update .to())

  • sbi/inference/potentials/base_potential.py
  • sbi/inference/potentials/likelihood_based_potential.py
  • sbi/inference/potentials/ratio_based_potential.py
  • sbi/inference/potentials/posterior_based_potential.py
  • sbi/inference/potentials/vector_field_potential.py
  • sbi/inference/potentials/vector_field_adaptor.py

Call Sites (remove .to() calls)

  • sbi/inference/posteriors/mcmc_posterior.py
  • sbi/inference/posteriors/vi_posterior.py
  • sbi/inference/posteriors/rejection_posterior.py
  • sbi/inference/posteriors/importance_posterior.py
  • sbi/samplers/vi/vi_divergence_optimizers.py

Posterior.to() updates (add direct component moves)

  • All posterior classes that override .to()

Additional Considerations

VI Optimizers (vi_divergence_optimizers.py)

The VI optimizer creates potentials during training. If we remove .to() from potentials, we need an alternative:

Option A: Move estimator/prior before creating potential

# In VI optimizer build
estimator = estimator.to(device)
prior = prior.to(device)
potential = LikelihoodBasedPotential(estimator, prior, x_o)
# potential already on correct device

Option B: Create utility function

def move_potential_components_to_device(potential, device):
    """Move all components of a potential to device."""
    if hasattr(potential, 'prior'):
        potential.prior = move_distribution_to_device(potential.prior, device)
    if hasattr(potential, 'likelihood_estimator'):
        potential.likelihood_estimator.to(device)
    # ... etc
    potential.device = device
    return potential

Recommendation: Option A - it's cleaner and follows the principle that device should be set at construction time.


Summary

  1. Add deprecation warning + NotImplementedError to BasePotential.to()
  2. Update/remove subclass .to() overrides
  3. Remove 7 internal call sites
  4. Ensure posterior.to() moves all components directly
  5. Handle VI optimizer case specially
  6. Test thoroughly

@Jocho-Smith

Copy link
Copy Markdown
Contributor Author

I don't understand what this codecov/patch means. What should I do with this?

@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.

I am a bit unsure about the idea here. You introduce a _move_estimator_to_device for each potential, but then in the posteriors you still move the potential.prior and potential.x_o to device manually. Shouldn't that be part of the move estimator method? This comment holds for all posterior file modifications.

Additionally, if we have to keep that logic, then can we consolidate it in the Base class? So we avoid code duplication in every class?

self.potential_fns[i].prior, device
)
if self.potential_fns[i]._x_o is not None:
self.potential_fns[i]._x_o = self.potential_fns[i]._x_o.to(device)

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.

Do we need to be explicit about x_o and prior here? Shouldn't the underlying estimator handle everything that is needed? Like e.g. the likleihood estimator?

def _move_estimator_to_device(
self, device: Union[str, torch.device]
) -> "LikelihoodBasedPotential":
self.likelihood_estimator = self.likelihood_estimator.to(device)

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 estimators are nn.Modules in all cases, right? Then an in-place operation for .to() is preferred.

def _move_estimator_to_device(
self, device: Union[str, torch.device]
) -> "RatioBasedPotential":
self.ratio_estimator = self.ratio_estimator.to(device)

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.

same as for the likelihood

def _move_estimator_to_device(
self, device: Union[str, torch.device]
) -> "VectorFieldBasedPotential":
self.vector_field_estimator = self.vector_field_estimator.to(device)

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.

same as for the likelihood

"""
return self._x_o

def to(self, device: Union[str, torch.device]) -> "BasePotential":

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.

I am unsure whether we would need a deprecation warning? If it is user facing, then probably yes.


def to(self, device: Union[str, torch.device]) -> "BasePotential":
"""Move prior and x_o to the given device.
def _move_estimator_to_device(

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 base class has the prior and set_x() call already. So the move_estimator_to_device could at least move x_o and prior to device, right?


def to(self, device: Union[str, torch.device]) -> "BasePotential":
"""Move prior and x_o to the given device.
def _move_estimator_to_device(

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.

Also, the method is called from outside, i.e. from the posterior methods. But the underscore prefix indicates that it is a private method. This is conflicting.

@Jocho-Smith

Copy link
Copy Markdown
Contributor Author

You introduce a _move_estimator_to_device for each potential, but then in the posteriors you still move the potential.prior and potential.x_o to device manually. Shouldn't that be part of the move estimator method?

This would just bring back to() but with a different name.


Also I just discovered that potential.to was modified in February this year. 8f91ca3#diff-4869f585fa4ce4ff8fdef3686aa348a959ae33d917f757766ef0ea0c7667769b

Maybe the question is what we try to achieve here in the first place 🤔

@Jocho-Smith

Copy link
Copy Markdown
Contributor Author

I started over here: #1970

@Jocho-Smith Jocho-Smith closed this Aug 4, 2026
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