Skip to content

removing .to for potential - #1970

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

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

Conversation

@Jocho-Smith

Copy link
Copy Markdown
Contributor

This is the second attempt to removing to() from the potential. First was here

Potentials are now immutable after creation, similar to how .bind() works.

Two Usage Patterns

Option 1: Move components first, then build potential

# Move estimator, prior, and x to device first
estimator = estimator.to(device)
prior = prior.to(device)
x_o = x_o.to(device)

# Build potential from already-moved components
potential, transform = some_potential_builder(estimator, prior)
bound_potential = potential.bind(x_o)

Option 2: Use posterior.to()

# Build posterior first
posterior = inference.build_posterior()

# Posterior.to() handles moving estimator, prior, and x internally
posterior.to(device)

This is the recommended approach as it handles all components automatically.

What Changed

  • .to() on potentials now shows a FutureWarning and does nothing
  • Posterior classes (DirectPosterior, MCMCPosterior, etc.) now rebuild their potential internally when .to() is called

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1f0c7cf0-2b7a-4dbd-94e9-0209a997b3f0

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 42.85714% with 36 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.65%. Comparing base (587f922) to head (7038f74).
⚠️ Report is 43 commits behind head on gsoc-2026.

Files with missing lines Patch % Lines
sbi/utils/user_input_checks_utils.py 39.58% 29 Missing ⚠️
sbi/inference/posteriors/importance_posterior.py 33.33% 2 Missing ⚠️
sbi/inference/posteriors/mcmc_posterior.py 33.33% 2 Missing ⚠️
sbi/inference/posteriors/rejection_posterior.py 33.33% 2 Missing ⚠️
sbi/inference/posteriors/vi_posterior.py 66.66% 1 Missing ⚠️
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     
Flag Coverage Δ
fast 81.42% <42.85%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/posteriors/ensemble_posterior.py 78.57% <ø> (-2.05%) ⬇️
sbi/inference/potentials/base_potential.py 83.01% <100.00%> (-9.84%) ⬇️
...inference/potentials/likelihood_based_potential.py 82.65% <100.00%> (+0.54%) ⬆️
.../inference/potentials/posterior_based_potential.py 88.70% <ø> (-7.66%) ⬇️
sbi/inference/potentials/ratio_based_potential.py 100.00% <ø> (ø)
sbi/inference/potentials/vector_field_potential.py 87.50% <ø> (-3.49%) ⬇️
sbi/inference/posteriors/vi_posterior.py 78.50% <66.66%> (-0.05%) ⬇️
sbi/inference/posteriors/importance_posterior.py 76.92% <33.33%> (+0.29%) ⬆️
sbi/inference/posteriors/mcmc_posterior.py 83.45% <33.33%> (-0.37%) ⬇️
sbi/inference/posteriors/rejection_posterior.py 76.78% <33.33%> (-1.40%) ⬇️
... and 1 more

... and 3 files with indirect coverage changes

@dgedon
dgedon requested review from dgedon and a lite review from Copilot and removed request for Copilot August 4, 2026 11:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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() assigns moved_estimator = estimator.to(device), but .to() is in-place for most torch modules and may return None. That would pass None into 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 passing x_o directly into the constructor. This resets _x_is_iid to the BasePotential default (True) and, for VectorFieldBasedPotential, does not rebuild the required flow/flows that 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 without flow(s)). Consider constructing an unbound potential and then rebinding with the original x_o and _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.

Comment thread sbi/utils/user_input_checks_utils.py Outdated
Comment on lines +75 to +77
This utility creates a new potential with the neural estimator moved to a new
device. It does NOT mutate the original potential.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 win

Relocate potential_fn during initialization.

The constructor moves _prior to device, but it leaves potential_fn on its original device. The constructor documentation states that all components are placed on device.

If the caller constructs VIPosterior with a CPU potential and device="cuda", train() can evaluate CUDA tensors with a CPU estimator before VIPosterior.to() is called.

Reconstruct potential_fn with potential_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

📥 Commits

Reviewing files that changed from the base of the PR and between e6f611e and ce48844.

📒 Files selected for processing (11)
  • sbi/inference/posteriors/ensemble_posterior.py
  • sbi/inference/posteriors/importance_posterior.py
  • sbi/inference/posteriors/mcmc_posterior.py
  • sbi/inference/posteriors/rejection_posterior.py
  • sbi/inference/posteriors/vi_posterior.py
  • sbi/inference/potentials/base_potential.py
  • sbi/inference/potentials/likelihood_based_potential.py
  • sbi/inference/potentials/posterior_based_potential.py
  • sbi/inference/potentials/ratio_based_potential.py
  • sbi/inference/potentials/vector_field_potential.py
  • sbi/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

Comment on lines 105 to +126
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,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +110 to +126
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)

@coderabbitai coderabbitai Bot Aug 4, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 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.py

Repository: 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 expanded

Repository: 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.py

Repository: 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.py

Repository: 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.py

Repository: 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 -20

Repository: 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 -20

Repository: 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')}")
PY

Repository: 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 -50

Repository: 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 -20

Repository: 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 -10

Repository: 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.py

Repository: 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.py

Repository: 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.py

Repository: 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 -40

Repository: 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.py

Repository: 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.py

Repository: 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.py

Repository: 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.

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 agree with this

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +115 to +123
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

@coderabbitai coderabbitai Bot Aug 4, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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 agree with this one

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +130 to +147
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,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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.

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.

Comment on lines +110 to +126
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)

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 agree with this

Comment on lines +132 to +138
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):

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.

We are missing the CustomPotentialWrapper here, no?

Returns:
Self for method chaining.
"""
import warnings

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.

import at file level

Comment on lines +115 to +123
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

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 agree with this one

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.

Are we missing this one?

@Jocho-Smith

Copy link
Copy Markdown
Contributor Author

I overlooked this error:

FAILED tests/vi_test.py::test_amortized_vi_with_fake_potential - 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.

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.

@Jocho-Smith
Jocho-Smith requested a review from dgedon August 10, 2026 13:54

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

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.

Comment on lines +153 to +182
# 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

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

@dgedon

dgedon commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

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.

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.

3 participants