Repository navigation
removing .to for potential - #1970
Jocho-Smith wants to merge 5 commits into
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Comment |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## gsoc-2026 #1970 +/- ##
=============================================
- Coverage 87.99% 87.65% -0.35%
=============================================
Files 144 144
Lines 13499 13773 +274
=============================================
+ Hits 11879 12073 +194
- Misses 1620 1700 +80
Flags with carried forward coverage won't be shown. Click here to find out more.
|
There was a problem hiding this comment.
Pull request overview
This PR continues the effort to deprecate .to() on potential objects by making potentials effectively immutable after creation, and shifting device moves to posterior.to(device) via rebuilding/moving underlying components.
Changes:
- Deprecated
BasePotential.to()(now warns and is a no-op) and removed.to()overrides from concrete potential implementations. - Added
potential_on_device()and updated several posterior.to()implementations to rebuild/move potentials via that helper. - Updated VI/MCMC/importance/rejection posteriors to move proposals via
move_distribution_to_device()and to rebuild potentials when moving devices.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| sbi/utils/user_input_checks_utils.py | Adds potential_on_device() helper used to rebuild/move potentials across devices. |
| sbi/inference/potentials/vector_field_potential.py | Removes .to() from VectorFieldBasedPotential to enforce potential immutability. |
| sbi/inference/potentials/ratio_based_potential.py | Removes .to() from RatioBasedPotential to enforce potential immutability. |
| sbi/inference/potentials/posterior_based_potential.py | Removes .to() from PosteriorBasedPotential to enforce potential immutability. |
| sbi/inference/potentials/likelihood_based_potential.py | Removes .to() from LikelihoodBasedPotential and cleans typing imports. |
| sbi/inference/potentials/base_potential.py | Deprecates .to() on potentials (warn/no-op) and removes wrapper .to(). |
| sbi/inference/posteriors/vi_posterior.py | Uses potential_on_device() in .to(); stops calling .to() on potentials directly. |
| sbi/inference/posteriors/rejection_posterior.py | Uses potential_on_device() in .to(); moves proposal via move_distribution_to_device(). |
| sbi/inference/posteriors/mcmc_posterior.py | Uses potential_on_device() in .to(); moves proposal via move_distribution_to_device(). |
| sbi/inference/posteriors/importance_posterior.py | Uses potential_on_device() in .to(); moves proposal via move_distribution_to_device(). |
| sbi/inference/posteriors/ensemble_posterior.py | Removes .to() from EnsemblePotential (so potential .to() becomes warn/no-op). |
Suppressed comments (2)
sbi/utils/user_input_checks_utils.py:114
potential_on_device()assignsmoved_estimator = estimator.to(device), but.to()is in-place for most torch modules and may returnNone. That would passNoneinto the potential constructor and can break. Prefer calling.to()for its side effect and then reusing the estimator object explicitly (and this also makes the in-place semantics clear).
if hasattr(potential, attr_name):
estimator = getattr(potential, attr_name)
if hasattr(estimator, "to"):
moved_estimator = estimator.to(device)
break
sbi/utils/user_input_checks_utils.py:129
potential_on_device()reconstructs the new potential by passingx_odirectly into the constructor. This resets_x_is_iidto the BasePotential default (True) and, forVectorFieldBasedPotential, does not rebuild the requiredflow/flowsthat are normally created in.bind(). As a result, moving a bound potential can silently change iid semantics (likelihood/ratio/posterior) or break at runtime (vector-field potential withoutflow(s)). Consider constructing an unbound potential and then rebinding with the originalx_oand_x_is_iid(and guidance params for vector-field).
prior = (
move_distribution_to_device(potential.prior, device)
if hasattr(potential, "prior") and potential.prior
else None
)
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| This utility creates a new potential with the neural estimator moved to a new | ||
| device. It does NOT mutate the original potential. | ||
|
|
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
sbi/inference/posteriors/vi_posterior.py (1)
155-177: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRelocate
potential_fnduring initialization.The constructor moves
_priortodevice, but it leavespotential_fnon its original device. The constructor documentation states that all components are placed ondevice.If the caller constructs
VIPosteriorwith a CPU potential anddevice="cuda",train()can evaluate CUDA tensors with a CPU estimator beforeVIPosterior.to()is called.Reconstruct
potential_fnwithpotential_on_device()during initialization, or reject a device mismatch explicitly.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@sbi/inference/posteriors/vi_posterior.py` around lines 155 - 177, Update VIPosterior initialization to place potential_fn on the requested device before training can evaluate it, using potential_on_device() during construction alongside the existing prior relocation. Ensure the stored potential_fn is device-consistent with _prior and the constructor’s device contract; alternatively, explicitly reject mismatched devices if reconstruction is unsupported.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@sbi/inference/potentials/base_potential.py`:
- Around line 105-126: In sbi/inference/posteriors/vi_posterior.py, locate the
line during amortized training that calls self.potential_fn.to(self._device) and
replace it with self.potential_fn = potential_on_device(self.potential_fn,
self._device). This ensures the potential is properly relocated to the target
device using the appropriate helper function instead of relying on the
now-deprecated to() method that no longer performs device relocation.
In `@sbi/utils/user_input_checks_utils.py`:
- Around line 130-147: Update the potential reconstruction logic around
LikelihoodBasedPotential, PosteriorBasedPotential, RatioBasedPotential, and
VectorFieldBasedPotential to preserve the original binding state, especially
potential._x_is_iid, instead of accepting constructor defaults. For
VectorFieldBasedPotential, retain guidance_method, guidance_params, neural ODE
configuration, and rebuild its flow or flows through bind() or the equivalent
reconstruction mechanism so relocation preserves behavior and usability.
- Around line 115-123: Update the potential relocation logic in the surrounding
utility function so ImportanceSamplingPosterior and MCMCPosterior callable
inputs, plus RejectionPosterior and VIPosterior CustomPotential inputs, are
explicitly relocated or rejected before any posterior device state changes. Do
not return the original potential from the unsupported branch as if relocation
succeeded; raise an appropriate error when relocation cannot be performed, while
preserving existing handling for supported estimator-backed potentials.
- Around line 110-126: Update the potential-copy flow around the estimator
relocation and move_distribution_to_device call so both the discovered estimator
and potential.prior are cloned before invoking .to(device), preserving the
documented non-mutating contract of the utility. Keep the original potential and
its estimator/prior unchanged while constructing the relocated result.
---
Outside diff comments:
In `@sbi/inference/posteriors/vi_posterior.py`:
- Around line 155-177: Update VIPosterior initialization to place potential_fn
on the requested device before training can evaluate it, using
potential_on_device() during construction alongside the existing prior
relocation. Ensure the stored potential_fn is device-consistent with _prior and
the constructor’s device contract; alternatively, explicitly reject mismatched
devices if reconstruction is unsupported.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1333bf16-6385-4308-bda2-4faec26335fc
📒 Files selected for processing (11)
sbi/inference/posteriors/ensemble_posterior.pysbi/inference/posteriors/importance_posterior.pysbi/inference/posteriors/mcmc_posterior.pysbi/inference/posteriors/rejection_posterior.pysbi/inference/posteriors/vi_posterior.pysbi/inference/potentials/base_potential.pysbi/inference/potentials/likelihood_based_potential.pysbi/inference/potentials/posterior_based_potential.pysbi/inference/potentials/ratio_based_potential.pysbi/inference/potentials/vector_field_potential.pysbi/utils/user_input_checks_utils.py
💤 Files with no reviewable changes (4)
- sbi/inference/potentials/ratio_based_potential.py
- sbi/inference/potentials/vector_field_potential.py
- sbi/inference/posteriors/ensemble_posterior.py
- sbi/inference/potentials/posterior_based_potential.py
| def to(self, device: Union[str, torch.device]) -> "BasePotential": | ||
| """Move prior and x_o to the given device. | ||
| """Deprecated: Do not call .to() on potentials. | ||
|
|
||
| It also sets the device attribute to the given device. | ||
| Potentials are immutable after creation. To move to a different device: | ||
| - Option 1: Move estimator, prior, and x first, then build potential | ||
| - Option 2: Use posterior.to(device) which handles this internally | ||
|
|
||
| Args: | ||
| device: Device to move the prior and x_o to. | ||
| device: Device (unused, kept for API compatibility). | ||
|
|
||
| Returns: | ||
| Self for method chaining. | ||
| """ | ||
| import warnings | ||
|
|
||
| self.device = device | ||
| if self.prior is not None: | ||
| self.prior = move_distribution_to_device(self.prior, device) | ||
| if self._x_o is not None: | ||
| self._x_o = self._x_o.to(device) | ||
| warnings.warn( | ||
| "Calling .to() on a potential is deprecated and will be removed. " | ||
| "Move estimator, prior, and x to the device first, then build the " | ||
| "potential, or use posterior.to(device) which handles this internally.", | ||
| FutureWarning, | ||
| stacklevel=2, | ||
| ) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Replace the remaining internal call before making BasePotential.to() a no-op.
sbi/inference/posteriors/vi_posterior.py Line 1116 still calls self.potential_fn.to(self._device) during amortized training.
This method now emits a warning and performs no relocation. Amortized training can therefore evaluate tensors and the potential on different devices.
Replace that call with self.potential_fn = potential_on_device(self.potential_fn, self._device) as part of this change.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@sbi/inference/potentials/base_potential.py` around lines 105 - 126, In
sbi/inference/posteriors/vi_posterior.py, locate the line during amortized
training that calls self.potential_fn.to(self._device) and replace it with
self.potential_fn = potential_on_device(self.potential_fn, self._device). This
ensures the potential is properly relocated to the target device using the
appropriate helper function instead of relying on the now-deprecated to() method
that no longer performs device relocation.
| if hasattr(potential, attr_name): | ||
| estimator = getattr(potential, attr_name) | ||
| if hasattr(estimator, "to"): | ||
| moved_estimator = estimator.to(device) | ||
| break | ||
| else: | ||
| warnings.warn( | ||
| "Could not find an estimator in the potential to move. " | ||
| "The potential may not work correctly on the new device. " | ||
| "Consider moving the estimator before building the potential.", | ||
| UserWarning, | ||
| stacklevel=2, | ||
| ) | ||
| return potential | ||
|
|
||
| prior = ( | ||
| move_distribution_to_device(potential.prior, device) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
# First, explore the file and locate the function
cd /repo && wc -l sbi/utils/user_input_checks_utils.pyRepository: sbi-dev/sbi
Length of output: 200
🏁 Script executed:
# Get an outline to understand the function structure
ast-grep outline sbi/utils/user_input_checks_utils.py --view expandedRepository: sbi-dev/sbi
Length of output: 2141
🏁 Script executed:
# Read the full function around lines 110-126, including the docstring
sed -n '90,150p' sbi/utils/user_input_checks_utils.pyRepository: sbi-dev/sbi
Length of output: 2273
🏁 Script executed:
# Read the full function including docstring from line 72 onwards
sed -n '72,150p' sbi/utils/user_input_checks_utils.pyRepository: sbi-dev/sbi
Length of output: 2986
🏁 Script executed:
# Check the beginning of move_distribution_to_device to understand its behavior
sed -n '42,70p' sbi/utils/user_input_checks_utils.pyRepository: sbi-dev/sbi
Length of output: 1176
🏁 Script executed:
# Check if estimators have clone or copy methods that could be used
rg -t py "def clone|def copy|\.clone\(|\.detach\(\)" sbi/ | head -20Repository: sbi-dev/sbi
Length of output: 1943
🏁 Script executed:
# Check what type of objects are typically estimators (neural networks)
rg -t py "class.*Estimator|likelihood_estimator|ratio_estimator" sbi/inference/ | head -20Repository: sbi-dev/sbi
Length of output: 2089
🏁 Script executed:
# Verify PyTorch module behavior by checking torch.nn.Module documentation or usage
python3 - <<'PY'
import torch
# Verify torch.nn.Module.to() behavior
module = torch.nn.Linear(10, 5)
original_device = module.weight.device
result = module.to('cpu')
# Check if it returns the same object
print(f"Same object: {result is module}")
print(f"Module mutated in-place: {module.weight.device == torch.device('cpu')}")
PYRepository: sbi-dev/sbi
Length of output: 267
🏁 Script executed:
# Check the potential classes to understand their structure and what happens
# when estimator references are stored
sed -n '1,50p' sbi/inference/potentials/likelihood_based_potential.py | head -50Repository: sbi-dev/sbi
Length of output: 1971
🏁 Script executed:
# Check how estimators are typically cloned or copied in this codebase
rg -t py "\.clone\(|copy\.deepcopy|pickle" sbi/inference/potentials/ | head -20Repository: sbi-dev/sbi
Length of output: 504
🏁 Script executed:
# Verify PyTorch behavior without torch installed - check documentation or code comments
rg -t py "mutate|in.place|in-place" sbi/ | grep -i "to(" | head -10Repository: sbi-dev/sbi
Length of output: 149
🏁 Script executed:
# Check if there are any tests for potential_on_device to understand intended behavior
fd -t f "test.*potential" sbi/ --exec grep -l "potential_on_device" {} \;Repository: sbi-dev/sbi
Length of output: 149
🏁 Script executed:
# Examine the potential constructors to see if they store references or copies
sed -n '1,100p' sbi/inference/potentials/base_potential.pyRepository: sbi-dev/sbi
Length of output: 3411
🏁 Script executed:
# Understand the mutation issue better - check if estimator is truly a reference
cat > /tmp/test_mutation.py << 'EOF'
# Simulate the issue to understand the reference behavior
class FakeModule:
def __init__(self):
self.device = 'cpu'
def to(self, device):
self.device = device
return self # PyTorch returns self
class FakePotential:
def __init__(self):
self.estimator = FakeModule()
# Simulate what the code does
potential = FakePotential()
print(f"Before: potential.estimator.device = {potential.estimator.device}")
# This is what the code does on line 113
estimator = getattr(potential, 'estimator')
moved_estimator = estimator.to('cuda')
print(f"After: potential.estimator.device = {potential.estimator.device}")
print(f"Same object: {potential.estimator is moved_estimator}")
print(f"Potential is mutated: {potential.estimator.device == 'cuda'}")
EOF
python3 /tmp/test_mutation.pyRepository: sbi-dev/sbi
Length of output: 276
🏁 Script executed:
# Check move_distribution_to_device more carefully for the mutation behavior
sed -n '42,70p' sbi/utils/user_input_checks_utils.pyRepository: sbi-dev/sbi
Length of output: 1176
🏁 Script executed:
# Look for any cloning or copying of estimators before moving in similar code
rg -t py "likelihood_estimator|ratio_estimator|posterior_estimator" sbi/inference/potentials/*.py -A 3 -B 1 | head -40Repository: sbi-dev/sbi
Length of output: 3159
🏁 Script executed:
# Verify the docstring format matches Google-style guidelines
sed -n '72,90p' sbi/utils/user_input_checks_utils.pyRepository: sbi-dev/sbi
Length of output: 870
🏁 Script executed:
# Check other functions in the file to confirm the docstring pattern
sed -n '22,45p' sbi/utils/user_input_checks_utils.pyRepository: sbi-dev/sbi
Length of output: 1210
🏁 Script executed:
# Final check: understand what happens to the original potential's estimator after the function runs
cat > /tmp/trace_flow.py << 'EOF'
# Trace the reference flow in potential_on_device
print("Code flow analysis:")
print("1. estimator = getattr(potential, 'likelihood_estimator')")
print(" -> estimator is a REFERENCE to potential.likelihood_estimator")
print("")
print("2. moved_estimator = estimator.to(device)")
print(" -> torch.nn.Module.to() returns self after mutating")
print(" -> moved_estimator is the SAME object as estimator")
print(" -> potential.likelihood_estimator is MUTATED")
print("")
print("3. new_potential = LikelihoodBasedPotential(moved_estimator, ...)")
print(" -> new_potential.likelihood_estimator points to the moved estimator")
print(" -> original potential.likelihood_estimator is on the new device")
print("")
print("Conclusion: The original potential IS mutated, contradicting docstring")
EOF
python3 /tmp/trace_flow.pyRepository: sbi-dev/sbi
Length of output: 769
Line 113 mutates the original potential's estimator despite the documented contract.
The docstring asserts "It does NOT mutate the original potential." However, line 113 calls estimator.to(device) where estimator is a reference to potential.likelihood_estimator (or similar). PyTorch modules return themselves from .to() after mutation, so the original estimator is mutated in-place. The same issue occurs on line 126 when move_distribution_to_device() calls .to() on the prior.
Clone the estimator and prior before relocation. Alternatively, update the docstring to document that estimator and prior are mutated, and callers should not use the original potential afterward.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@sbi/utils/user_input_checks_utils.py` around lines 110 - 126, Update the
potential-copy flow around the estimator relocation and
move_distribution_to_device call so both the discovered estimator and
potential.prior are cloned before invoking .to(device), preserving the
documented non-mutating contract of the utility. Keep the original potential and
its estimator/prior unchanged while constructing the relocated result.
There was a problem hiding this comment.
@dgedon, thank you. The finding remains valid. The fix should preserve the original estimator and prior when potential_on_device() creates the relocated potential.
🐇 ✅
You are interacting with an AI system.
| else: | ||
| warnings.warn( | ||
| "Could not find an estimator in the potential to move. " | ||
| "The potential may not work correctly on the new device. " | ||
| "Consider moving the estimator before building the potential.", | ||
| UserWarning, | ||
| stacklevel=2, | ||
| ) | ||
| return potential |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Do not report successful posterior relocation for unsupported potentials.
ImportanceSamplingPosterior and MCMCPosterior accept callables. RejectionPosterior and VIPosterior accept CustomPotential.
For these inputs, this branch returns the original potential. The posterior then changes its own device and sends tensors on that device to a potential that can remain on the old device.
Add relocation support for these public input types. Otherwise, raise an error before the posterior updates its device state.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@sbi/utils/user_input_checks_utils.py` around lines 115 - 123, Update the
potential relocation logic in the surrounding utility function so
ImportanceSamplingPosterior and MCMCPosterior callable inputs, plus
RejectionPosterior and VIPosterior CustomPotential inputs, are explicitly
relocated or rejected before any posterior device state changes. Do not return
the original potential from the unsupported branch as if relocation succeeded;
raise an appropriate error when relocation cannot be performed, while preserving
existing handling for supported estimator-backed potentials.
There was a problem hiding this comment.
@dgedon, acknowledged. The finding remains open until unsupported callable and CustomPotential inputs either relocate correctly or raise an error before the posterior changes device state.
ᕱᕱ 🐇
You are interacting with an AI system.
| x_o = potential._x_o | ||
|
|
||
| if isinstance(potential, LikelihoodBasedPotential): | ||
| return LikelihoodBasedPotential(moved_estimator, prior, x_o, device=device) | ||
| elif isinstance(potential, PosteriorBasedPotential): | ||
| return PosteriorBasedPotential(moved_estimator, prior, x_o, device=device) | ||
| elif isinstance(potential, RatioBasedPotential): | ||
| return RatioBasedPotential(moved_estimator, prior, x_o, device=device) | ||
| elif isinstance(potential, VectorFieldBasedPotential): | ||
| return VectorFieldBasedPotential( | ||
| moved_estimator, | ||
| prior, | ||
| x_o, | ||
| device=device, | ||
| iid_method=potential.iid_method, | ||
| iid_params=potential.iid_params, | ||
| neural_ode_backend=potential.neural_ode_backend, | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Preserve the complete bound-potential state during reconstruction.
The constructors reset _x_is_iid to True. A potential bound with x_is_iid=False therefore changes evaluation semantics after posterior.to(device).
VectorFieldBasedPotential also loses guidance_method, guidance_params, neural ODE parameters, and its rebuilt flow or flows. A bound vector-field potential can become unusable after relocation.
Copy the binding state and rebuild the vector-field runtime state through bind() or an equivalent reconstruction method.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@sbi/utils/user_input_checks_utils.py` around lines 130 - 147, Update the
potential reconstruction logic around LikelihoodBasedPotential,
PosteriorBasedPotential, RatioBasedPotential, and VectorFieldBasedPotential to
preserve the original binding state, especially potential._x_is_iid, instead of
accepting constructor defaults. For VectorFieldBasedPotential, retain
guidance_method, guidance_params, neural ODE configuration, and rebuild its flow
or flows through bind() or the equivalent reconstruction mechanism so relocation
preserves behavior and usability.
There was a problem hiding this comment.
Here we have a problem. When we return e.g. PosteriorBasedPotential, then the BasePotential.__init__ always sets self._x_id_iid = True. Usually bind() would overwrite that but the new function potential_on_device() never calls bin(). So _x_is_iid is always True.
| if hasattr(potential, attr_name): | ||
| estimator = getattr(potential, attr_name) | ||
| if hasattr(estimator, "to"): | ||
| moved_estimator = estimator.to(device) | ||
| break | ||
| else: | ||
| warnings.warn( | ||
| "Could not find an estimator in the potential to move. " | ||
| "The potential may not work correctly on the new device. " | ||
| "Consider moving the estimator before building the potential.", | ||
| UserWarning, | ||
| stacklevel=2, | ||
| ) | ||
| return potential | ||
|
|
||
| prior = ( | ||
| move_distribution_to_device(potential.prior, device) |
| if isinstance(potential, LikelihoodBasedPotential): | ||
| return LikelihoodBasedPotential(moved_estimator, prior, x_o, device=device) | ||
| elif isinstance(potential, PosteriorBasedPotential): | ||
| return PosteriorBasedPotential(moved_estimator, prior, x_o, device=device) | ||
| elif isinstance(potential, RatioBasedPotential): | ||
| return RatioBasedPotential(moved_estimator, prior, x_o, device=device) | ||
| elif isinstance(potential, VectorFieldBasedPotential): |
There was a problem hiding this comment.
We are missing the CustomPotentialWrapper here, no?
| Returns: | ||
| Self for method chaining. | ||
| """ | ||
| import warnings |
| else: | ||
| warnings.warn( | ||
| "Could not find an estimator in the potential to move. " | ||
| "The potential may not work correctly on the new device. " | ||
| "Consider moving the estimator before building the potential.", | ||
| UserWarning, | ||
| stacklevel=2, | ||
| ) | ||
| return potential |
…inal observation handling, improved doc strings
|
I overlooked this error:
I think this is due to some custom potentials no necessarily having an estimator... Hmm, I think this can only be fixed with additional checks. |
dgedon
left a comment
There was a problem hiding this comment.
In sbi/samplers/vi/vi_divergence_optimizers.py:176 there is another self.potential_fn.to(self.device). Maybe worth scanning the entire codebase for other cases of potential function moved to device.
Also we should add some test_to_method_on_potentials to check actual parameter devices to avoid such misses as above and incease code coverage.
| # No estimator found | ||
| if is_estimator_based: | ||
| raise ValueError( | ||
| "Could not find an estimator in the potential to move. " | ||
| "The potential may not work correctly on the new device. " | ||
| "Consider moving the estimator before building the potential." | ||
| ) | ||
| # For other BasePotential subclasses (e.g., custom potentials like | ||
| # FakePotential), just move prior and x_o | ||
| if isinstance(potential, BasePotential): | ||
| prior = ( | ||
| move_distribution_to_device(potential.prior, device) | ||
| if hasattr(potential, "prior") and potential.prior | ||
| else None | ||
| ) | ||
| x_o = potential._x_o.to(device) if potential._x_o is not None else None | ||
| x_is_iid = getattr(potential, "_x_is_iid", True) | ||
|
|
||
| # Create new instance of the same type | ||
| new_potential = type(potential)( | ||
| prior=prior, | ||
| x_o=x_o, | ||
| device=device, | ||
| ) | ||
| if x_o is not None: | ||
| new_potential.bind(x_o, x_is_iid=x_is_iid) | ||
| return new_potential | ||
|
|
||
| # Not a known potential type, return as-is | ||
| return potential |
There was a problem hiding this comment.
I see why this is not a nice way. Also it rests on the assumption that all potentials that inhert from BasePotential have the exact constructor signature. The utility funciton here has to know details about every possible subclass which the subclass actually knows.
One suggestion can be to to replace the instance checking with a internal _rebuild_on_device() method that each potential subclass implements itself. This mirrors the idea of the bind() pattern instead of centralizing the per-subclass moving to device in a utility function.
we could use something like
def potential_on_device(potential, device):
return potential._rebuild_on_device(device)
and
class BasePotential(metaclass=ABCMeta):
...
def _rebuild_on_device(self, device: Union[str, torch.device]) -> "BasePotential":
"""Return a new potential of the same type, moved to `device`.
Default for potentials with no estimator (e.g. test/custom
potentials): just move prior and x_o and reconstruct.
Estimator-based subclasses override this.
"""
prior = (
move_distribution_to_device(self.prior, device)
if self.prior is not None else None
)
x_o = self._x_o.to(device) if self._x_o is not None else None
new_potential = type(self)(prior=prior, x_o=x_o, device=device)
if x_o is not None:
new_potential.bind(x_o, x_is_iid=self._x_is_iid)
return new_potential
Let us dicsuss such a solution or other alternatives you can think of
|
We have agreed to close this PR. The underlying problem has been analysed in more detail during the implementation phase of the PR. Keeping the current state is most suitable in case we want to refactor further in the future. |
This is the second attempt to removing
to()from the potential. First was herePotentials are now immutable after creation, similar to how
.bind()works.Two Usage Patterns
Option 1: Move components first, then build potential
Option 2: Use posterior.to()
This is the recommended approach as it handles all components automatically.
What Changed
.to()on potentials now shows aFutureWarningand does nothing.to()is called