Repository navigation
first attempt to remove potential.to and let the poeterior handle it - #1949
Jocho-Smith wants to merge 8 commits into
Conversation
…er has set the devices correctly
|
(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:
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 Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more.
|
|
ChatGPT also suggested another way of solving this. Maybe this is also an interesting solution. see hereMigration: Remove
|
| 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 elsewhere3.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 estimatorNote: The VI optimizer case is different - it's not inside a posterior.to() call. Options:
- Move estimator/prior to device before constructing the potential
- 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 movesNew 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:
-
No direct potential.to() calls remain:
grep -r "potential_fn\.to\|potential\.to" sbi/ --include="*.py"
-
All posterior.to() work correctly - run existing tests:
pytest tests/ -k "test_posterior_to" # or similar
-
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.pysbi/inference/potentials/likelihood_based_potential.pysbi/inference/potentials/ratio_based_potential.pysbi/inference/potentials/posterior_based_potential.pysbi/inference/potentials/vector_field_potential.pysbi/inference/potentials/vector_field_adaptor.py
Call Sites (remove .to() calls)
sbi/inference/posteriors/mcmc_posterior.pysbi/inference/posteriors/vi_posterior.pysbi/inference/posteriors/rejection_posterior.pysbi/inference/posteriors/importance_posterior.pysbi/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 deviceOption 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 potentialRecommendation: Option A - it's cleaner and follows the principle that device should be set at construction time.
Summary
- Add deprecation warning + NotImplementedError to
BasePotential.to() - Update/remove subclass
.to()overrides - Remove 7 internal call sites
- Ensure posterior.to() moves all components directly
- Handle VI optimizer case specially
- Test thoroughly
|
I don't understand what this |
dgedon
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
same as for the likelihood
| """ | ||
| return self._x_o | ||
|
|
||
| def to(self, device: Union[str, torch.device]) -> "BasePotential": |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
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 🤔 |
|
I started over here: #1970 |
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:
Option 2: Use posterior.to(device)
Note: the
_move_estimator_to_deviceseems 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