Skip to content

fix: reconcile posterior._device after torch.load with map_location - #1959

Closed
BHARATH0153 wants to merge 12 commits into
sbi-dev:mainfrom
BHARATH0153:fix-stale-device-clean
Closed

BHARATH0153 wants to merge 12 commits into
sbi-dev:mainfrom
BHARATH0153:fix-stale-device-clean

Conversation

@BHARATH0153

@BHARATH0153 BHARATH0153 commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1954

After torch.load(..., map_location=...) the model weights end up on the new device, but _device / potential_fn.device stay stale, so sample() and potential() fail with cross-device errors.

NeuralPosterior.setstate now checks where the tensors actually are and moves everything over (potential, prior, proposal, estimator, observation). VIPosterior.setstate delegates to it, so all posterior types are covered.

Added GPU round-trip tests for direct/rejection/importance/MCMC/VI/vector-field posteriors. Ran them locally on MPS since CI skips gpu-marked tests.

AI USAGE

used for testing and formatting by coderabbit

@BHARATH0153
BHARATH0153 marked this pull request as draft July 30, 2026 14:38
@BHARATH0153
BHARATH0153 force-pushed the fix-stale-device-clean branch 2 times, most recently from d49b99c to c50e4d8 Compare July 30, 2026 14:41
@BHARATH0153
BHARATH0153 marked this pull request as ready for review July 30, 2026 14:43
@codecov

codecov Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 42.55319% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.92%. Comparing base (aa9f5af) to head (eab3e1e).
⚠️ Report is 14 commits behind head on main.

Files with missing lines Patch % Lines
sbi/inference/posteriors/base_posterior.py 30.43% 16 Missing ⚠️
sbi/utils/torchutils.py 52.17% 11 Missing ⚠️

❌ Your patch check has failed because the patch coverage (42.55%) is below the target coverage (50.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1959      +/-   ##
==========================================
+ Coverage   88.81%   88.92%   +0.11%     
==========================================
  Files         139      143       +4     
  Lines       13520    15617    +2097     
==========================================
+ Hits        12008    13888    +1880     
- Misses       1512     1729     +217     
Flag Coverage Δ
fast 83.34% <42.55%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/posteriors/vi_posterior.py 85.25% <100.00%> (ø)
sbi/utils/torchutils.py 77.97% <52.17%> (-0.13%) ⬇️
sbi/inference/posteriors/base_posterior.py 72.54% <30.43%> (-12.64%) ⬇️

... and 29 files with indirect coverage changes

@BHARATH0153
BHARATH0153 marked this pull request as draft July 30, 2026 14:56
@BHARATH0153
BHARATH0153 force-pushed the fix-stale-device-clean branch from c50e4d8 to 3785286 Compare July 30, 2026 14:58
@BHARATH0153
BHARATH0153 force-pushed the fix-stale-device-clean branch from 3785286 to 2a3f8b6 Compare July 30, 2026 15:01
@BHARATH0153
BHARATH0153 marked this pull request as ready for review July 30, 2026 15:03
@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@janfb once look into these when you are free thanks!

@janfb

janfb commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Thanks for taking this on @BHARATH0153 . Overall, __setstate__ is the right lever for this, and the
DirectPosterior case now updates correctly, good!
I ran your branch on my MPS machine locally to test for the other posteriors as well (our PR CI runs with -m "not slow and not gpu", so it never executes gpu-marked tests). My run found gaps that we have to close before this can go in.

1. The VI test has never run.

VIPosterior(posterior) is not a valid call. The first argument must be a
potential_fn. The test fails before it reaches the save:

ValueError: We could not find a suitable prior distribution within `potential_fn`
or `q` (if a VIPosterior is given). Please explicitly specify a prior.

Please always run gpu-marked tests on your machine before you push. CI cannot catch these failures.

2. The fix cannot reach VIPosterior.

VIPosterior got its own __setstate__ in #1953. Pickle calls that method, not
the base method. So your fix never runs for VI, also with a correct test. I
verified this: after a roundtrip with map_location="cpu", _device is still
mps:0. I think VIPosterior.__setstate__ should call
super().__setstate__(state_dict) instead of setting self.__dict__ itself.

3. The fix does nothing for the potential-based posteriors.

The potential classes are not nn.Modules. They have no parameters method. So
getattr(potential_fn, "parameters", None) always returns None, and the method
exits without effect. This hits MCMCPosterior, RejectionPosterior, and
ImportanceSamplingPosterior. I verified it for MCMCPosterior: after loading,
_device is still mps:0. Relatedly, VectorFieldPosterior stores its net as
vector_field_estimator, so your probe misses it too. Issue #1954 says the bug
affects every posterior type. So the fix should cover all of them.

4. For DirectPosterior, the fix repairs only part of the state.

potential_fn.device stays stale. _device shows cpu and sample() works.
But potential() fails:

loaded.potential(zeros(1, 2))
# RuntimeError: Expected all tensors to be on the same device,
# but found at least two devices, mps:0 and cpu!

The .to() methods from #1958 list the attributes that hold device state:
_device, potential_fn.device, the prior, and x_o. I think __setstate__
must update the same attributes. The clean way is to reuse .to() after the state
is restored, not to copy parts of it. One problem stands in the way:
DirectPosterior.to() rejects priors without a .to() method. A plain
MultivariateNormal prior raises a ValueError. BasePotential.to() handles
this case with move_distribution_to_device(). I will open a separate issue for
that. Your fix can then build on it.

5. Small points.

  • The new docstring points to check_warn_and_setstate(). That function does not
    exist in the codebase.
  • The PR description still mentions the save/load guide cleanup. Commit 3573b5f
    reverted it. Please update the description.

@janfb

janfb commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

One more point @BHARATH0153 , separate from the review above. I want to share a few habits that
help us work together.

We are a small maintainer team, but our review time is very limited. You bring a lot of initiative, which is great, and #1888 and #1896 were useful fixes. With the points below, your initiative turns into merged PRs faster.

  • Please focus on one PR at a time. Our review bandwidth is the bottleneck, not
    your speed. Three open PRs from one author do not get three times the review
    time. One complete and verified PR moves through review fast.
  • Run every new test on your machine before you push. This is especially important for GPU-tests. CI does not run
    gpu-marked tests. The VI test in this PR fails at construction, so it has never run. When we find
    this in review, it costs the most time for everyone.
  • Answer open review questions before you ask for a new review. For example,
    Jocho's question on fix: suppress nested progress bars via thread-local context manager  #1922 is still open: "How exactly did you test this?"
  • Reminder pings do not move a PR up the queue. I usually review within about two weeks. After that, one friendly
    ping is welcome.
  • When someone else has a PR on an issue, please leave the issue with them. There is enough work for everyone. I am happy to point you to a good open issue.
  • AI tools are fine, I use them too. But you are responsible for every line and every test in your PR. With AI-help, one can file a PR for a bug fix within minutes easily. But if it is not checked carefully and fully understood by you, it can cause much more reviewing time and frustration on our end. Please state substantial AI help in the PR summary, and write how you tested the code.

None of this is meant to slow you down. The opposite: when a PR comes with the
verification done, we can review it fast, and it gets merged fast.

cheers, Jan

NeuralPosterior.__setstate__ now inspects the loaded object and moves the
potential function, prior, proposal, estimators, and observation to the
device implied by map_location whenever the stored _device string no
longer matches the actual device of the underlying tensors. This covers
posteriors that build their device state lazily or store it outside the
base class, including VIPosterior (own __setstate__) and
VectorFieldPosterior.

A new infer_tensor_device helper walks the object graph to recover the
device of parameters, buffers, and tensors. Tests exercise the
map_location round trip for direct, rejection, importance, MCMC, VI, and
vector field posteriors.
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Draft detected.

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: aa937882-8aaa-4df3-ba4a-07e247aa3669

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

Walkthrough

The change adds recursive device inference and applies it during posterior deserialization. Loaded posterior metadata, modules, distributions, potentials, and stored observations are reconciled with mapped tensor devices. Tests cover multiple posterior types loaded onto CPU.

Changes

Posterior device reconciliation

Layer / File(s) Summary
Device inference and posterior restoration
sbi/utils/torchutils.py, sbi/inference/posteriors/base_posterior.py, sbi/inference/posteriors/vi_posterior.py
infer_tensor_device traverses tensor-bearing objects. NeuralPosterior.__setstate__ synchronizes device metadata and posterior components after loading. VIPosterior delegates restoration to the parent implementation.
Mapped-load validation
tests/inference_on_device_test.py
Serialization tests verify CPU reconciliation, sampling, potential evaluation, and tensor placement across posterior types.

Estimated code review effort: 3 (Moderate) | ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main fix for stale posterior device state after torch.load with map_location.
Description check ✅ Passed The description explains the device reconciliation fix and the related serialization tests.
Linked Issues check ✅ Passed The changes address issue #1954 by synchronizing device state across posterior types and adding cross-device loading tests.
Out of Scope Changes check ✅ Passed The implementation and tests are directly related to the linked issue and stated pull request objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@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: 1

🤖 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/posteriors/vi_posterior.py`:
- Around line 1392-1402: Update VIPosterior.__setstate__ to call the parent
restoration first, then invoke VIPosterior.to() so non-module distributions are
moved and link_transform plus _q._link_transform are rebuilt using the restored
_device. Preserve the existing state_dict delegation and ensure reconciliation
happens only after NeuralPosterior.__setstate__ completes.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e54a9a49-f646-4969-bcee-9414535c330c

📥 Commits

Reviewing files that changed from the base of the PR and between aa9f5af and 4b119d2.

📒 Files selected for processing (4)
  • sbi/inference/posteriors/base_posterior.py
  • sbi/inference/posteriors/vi_posterior.py
  • sbi/utils/torchutils.py
  • tests/inference_on_device_test.py

@BHARATH0153

BHARATH0153 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review @janfb — all five points are addressed in commits 4b119d2 / ddfeeba on fix-stale-device-clean
I ran all gpu-marked tests locally on MPS before pushing this time, and pyright sbi is clean. Noted on keeping to one PR at a time.

The new __setstate__ logic was only exercised by gpu-marked tests, which CI
skips, leaving patch coverage below the threshold. Add cpu-only tests:

- tamper _device and potential_fn.device with a stale string before
  saving, then assert __setstate__ reconciles them after loading.
- unit tests for infer_tensor_device across modules, buffers, containers,
  plain attributes, and cyclic graphs.
@BHARATH0153
BHARATH0153 marked this pull request as draft August 4, 2026 12:21
@BHARATH0153
BHARATH0153 marked this pull request as ready for review August 4, 2026 12:26
The cpu-only save/load test already exercises the reconciliation, and CI
collects coverage for sbi source only, so the standalone unit tests added
no value for the patch threshold.
@BHARATH0153
BHARATH0153 marked this pull request as draft August 4, 2026 12:44
The gpu-marked round-trip tests already cover the fix; this test was added
only to satisfy the patch coverage threshold and is not needed.
@BHARATH0153
BHARATH0153 marked this pull request as ready for review August 4, 2026 12:45
@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '=== PR metadata ==='
gh pr view 1959 --repo sbi-dev/sbi --json title,body,headRefName,commits --jq '{title, headRefName, body, commits: [.commits[].oid]}'

echo
echo '=== Issue `#1954` ==='
gh issue view 1954 --repo sbi-dev/sbi --json title,body,state,url --jq '{title,state,url,body}'

echo
echo '=== Changed files and diff stat ==='
git diff --stat origin/main...HEAD
git diff --name-only origin/main...HEAD

echo
echo '=== Outlines ==='
ast-grep outline sbi/inference/posteriors/base_posterior.py --items all --view compact
ast-grep outline sbi/inference/posteriors/vi_posterior.py --items all --view compact
ast-grep outline sbi/utils/torchutils.py --items all --view compact
ast-grep outline tests/inference_on_device_test.py --items all --view compact

echo
echo '=== Focused diff ==='
git diff --unified=80 origin/main...HEAD -- \
  sbi/inference/posteriors/base_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/utils/torchutils.py \
  tests/inference_on_device_test.py

Length of output: 6779


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '=== Outlines ==='
ast-grep outline sbi/inference/posteriors/base_posterior.py --items all --view signatures
ast-grep outline sbi/inference/posteriors/vi_posterior.py --items all --view signatures
ast-grep outline sbi/utils/torchutils.py --items all --view signatures
ast-grep outline tests/inference_on_device_test.py --items all --view signatures

echo
echo '=== Focused diff ==='
git diff --unified=100 origin/main...HEAD -- \
  sbi/inference/posteriors/base_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/utils/torchutils.py \
  tests/inference_on_device_test.py

echo
echo '=== Current device migration methods ==='
rg -n -A100 -B10 '^\s*def (to|__setstate__)\(' \
  sbi/inference/posteriors/base_posterior.py \
  sbi/inference/posteriors/direct_posterior.py \
  sbi/inference/posteriors/mcmc_posterior.py \
  sbi/inference/posteriors/rejection_posterior.py \
  sbi/inference/posteriors/importance_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/inference/posteriors/vector_field_posterior.py

echo
echo '=== Device helper definitions and call sites ==='
rg -n -A35 -B5 '\b(infer_tensor_device|move_distribution_to_device)\b' \
  sbi/utils/torchutils.py \
  sbi/inference/posteriors \
  tests/inference_on_device_test.py

Length of output: 136839


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '=== Posterior device attributes and uses ==='
rg -n -A4 -B4 '\bself\.(device|_device|_prior|_map|_trained_on|theta_transform|link_transform)\b' \
  sbi/inference/posteriors/base_posterior.py \
  sbi/inference/posteriors/direct_posterior.py \
  sbi/inference/posteriors/mcmc_posterior.py \
  sbi/inference/posteriors/rejection_posterior.py \
  sbi/inference/posteriors/importance_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/inference/posteriors/vector_field_posterior.py

echo
echo '=== Potential device migration ==='
rg -n -A110 -B10 '^\s*def to\(' \
  sbi/inference/potentials/base_potential.py \
  sbi/inference/potentials/posterior_based_potential.py \
  sbi/inference/potentials/likelihood_based_potential.py \
  sbi/inference/potentials/ratio_based_potential.py \
  sbi/inference/potentials/vector_field_potential.py

echo
echo '=== Test execution after map-location load ==='
sed -n '980,1135p' tests/inference_on_device_test.py

echo
echo '=== Current PR review comments ==='
gh pr view 1959 --repo sbi-dev/sbi --comments

Length of output: 143922


@BHARATH0153 No. The latest commits address several requested items, but the PR does not yet fully address Jan’s review or #1954.

Completed:

  • The VI test now constructs VIPosterior with potential_fn and prior.
  • VIPosterior.__setstate__ delegates to NeuralPosterior.__setstate__.
  • Potential-based posteriors now reach reconciliation through potential_fn.to(...).
  • potential_fn.device is updated.
  • The PR description removes the reverted guide work and includes AI assistance plus MPS test information.

Still unresolved:

  • VIPosterior.__setstate__ does not call VIPosterior.to(loaded._device) after the base restoration. Therefore it does not reconcile VI-specific state such as _prior, link_transform, _q._link_transform, _map, and _trained_on. This matches the open CodeRabbit finding.
  • NeuralPosterior.__setstate__ updates _device but not subclass device. VectorFieldPosterior.sample() uses self.device at Line 371. After map_location="cpu", it can still use the old accelerator device.
  • The VI and vector-field tests do not call sample() or potential() after loading. They only check metadata and parameter placement. They cannot detect the two problems above.

Please fix these items and add end-to-end mapped-load assertions for VI and vector-field posteriors before requesting approval.

You are interacting with an AI system.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

@BHARATH0153 No. The latest commits address several of Jan’s requested changes, but the PR does not yet fully address Jan’s review or #1954.

Completed items include:

  • The VI test now provides potential_fn and prior.
  • VIPosterior.__setstate__ calls the base implementation.
  • Potential-based posteriors now enter device reconciliation.
  • potential_fn.device is updated.
  • The PR description removes the reverted guide work and states AI assistance and MPS testing.

The remaining required changes are:

  1. VIPosterior.__setstate__ must also reconcile VI-specific state after loading. This includes _prior, link_transform, _q._link_transform, _map, and _trained_on. Calling VIPosterior.to(loaded._device) after base restoration is the expected approach.

  2. The base restoration updates _device, but it does not update subclass device. VectorFieldPosterior.sample() uses self.device. After torch.load(..., map_location="cpu"), it can still select the old accelerator device.

  3. The VI and vector-field tests must call sample() and potential() after loading. Parameter-placement assertions alone do not verify that mapped loading works at runtime.

Please address these points before requesting approval. 🐇

You are interacting with an AI system.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

@BHARATH0153 No. The latest commits fix several of Jan’s requested items, but they do not yet cover all requirements from Jan’s review or issue #1954.

Remaining items:

  1. VIPosterior.__setstate__ does not reconcile VI-specific state after loading. It must update fields such as _prior, link_transform, _q._link_transform, _map, and _trained_on. Calling VIPosterior.to(loaded._device) after base restoration is the expected approach.

  2. VectorFieldPosterior.device remains stale after map_location="cpu". VectorFieldPosterior.sample() uses self.device, so it can still select the old accelerator device.

  3. The VI and vector-field tests must call sample() and potential() after loading. Current assertions only inspect metadata and parameter devices, so they do not detect these runtime failures.

Please address these items and add the end-to-end mapped-load assertions before requesting approval.

You are interacting with an AI system.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '=== PR metadata ==='
gh pr view 1959 --repo sbi-dev/sbi --json title,body,commits,files --jq '{title, body, commits: [.commits[].oid], files: [.files[].path]}'

echo '=== Changed-file diff ==='
git diff --unified=50 HEAD^...HEAD -- \
  sbi/inference/posteriors/base_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/utils/torchutils.py \
  tests/inference_on_device_test.py

echo '=== Relevant source outlines ==='
ast-grep outline sbi/inference/posteriors/base_posterior.py --items all --type method,function --match '__setstate__|to'
ast-grep outline sbi/inference/posteriors/vi_posterior.py --items all --type method,function --match '__setstate__|to'
ast-grep outline sbi/inference/posteriors --items all --type method --match 'to'

echo '=== Device-state references ==='
rg -n -C 4 --glob '*.py' \
  'vector_field_estimator|def __setstate__|def to\(|potential_fn\.device|move_distribution_to_device|infer_tensor_device' \
  sbi/inference/posteriors sbi/utils/torchutils.py tests/inference_on_device_test.py

Length of output: 46451


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '=== Issue `#1954` ==='
gh issue view 1954 --repo sbi-dev/sbi --json title,body,comments --jq '{title, body, comments: [.comments[] | {author: .author.login, body}]}'

echo '=== Full PR diff from merge base ==='
base_sha="$(gh pr view 1959 --repo sbi-dev/sbi --json baseRefOid --jq .baseRefOid)"
git diff --unified=35 "$base_sha"...HEAD -- \
  sbi/inference/posteriors/base_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/utils/torchutils.py \
  tests/inference_on_device_test.py

echo '=== Exact reconciliation implementations ==='
sed -n '334,390p' sbi/inference/posteriors/base_posterior.py
sed -n '1392,1415p' sbi/inference/posteriors/vi_posterior.py
sed -n '219,285p' sbi/utils/torchutils.py

echo '=== Exact new tests ==='
sed -n '970,1135p' tests/inference_on_device_test.py

echo '=== VectorField device fields and sampling paths ==='
sed -n '88,145p' sbi/inference/posteriors/vector_field_posterior.py
sed -n '345,385p' sbi/inference/posteriors/vector_field_posterior.py

Length of output: 42288


@BHARATH0153: The PR addresses most of @janfb’s requests and the main requirement in #1954.

Requested item Status
Correct VI test construction Covered
Make VIPosterior.__setstate__ call the base implementation Covered
Detect devices for potential-based posteriors Covered through recursive tensor detection
Update potential_fn.device and evaluate potential() after loading Covered
Handle prior, proposal, estimators, and _x Covered
Handle vector_field_estimator Covered
Remove the stale guide work from the PR description Covered
Disclose AI assistance and local GPU testing Covered

One gap remains for VectorFieldPosterior.

VectorFieldPosterior has both _device and device. The restoration code updates _device, but it does not update device. The SDE sampling path uses self.device:

ts = ts.to(self.device)

After torch.load(..., map_location="cpu"), self.device can still be mps:0 or cuda:0. This can cause SDE sampling to move ts back to the accelerator.

The vector-field test also only checks attributes. It does not call sample() or potential() after loading. Add an assertion for loaded.device == "cpu" and run a supported sampling path after loading. Then the PR will cover the requested device-state synchronization more completely.

You are interacting with an AI system.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== PR metadata and description =='
gh pr view 1959 --repo sbi-dev/sbi --json number,title,body,headRefName,commits --jq '{number,title,headRefName,body,commits:[.commits[].oid]}'

echo '== Issue `#1954` =='
gh issue view 1954 --repo sbi-dev/sbi --json number,title,body,comments --jq '{number,title,body,comments:[.comments[].body]}'

echo '== Current changed files =='
git diff --name-status origin/main...HEAD

echo '== Current PR diff =='
git diff --unified=80 origin/main...HEAD -- \
  sbi/inference/posteriors/base_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/utils/torchutils.py \
  tests/inference_on_device_test.py

echo '== Relevant declarations =='
ast-grep outline sbi/inference/posteriors/base_posterior.py --items all --type method,function --match '__setstate__|to'
ast-grep outline sbi/inference/posteriors/vi_posterior.py --items all --type method,function --match '__setstate__|to'
ast-grep outline sbi/inference/posteriors --items all --type method,function --match '__setstate__|to'

Length of output: 44503


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== BasePotential device migration =='
ast-grep outline sbi/inference/potentials/base_potential.py --items all --type method --match 'to|set_x|return_x_o'
sed -n '1,260p' sbi/inference/potentials/base_potential.py

echo '== Posterior-specific device migration implementations =='
for file in \
  sbi/inference/posteriors/direct_posterior.py \
  sbi/inference/posteriors/rejection_posterior.py \
  sbi/inference/posteriors/importance_posterior.py \
  sbi/inference/posteriors/mcmc_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/inference/posteriors/vector_field_posterior.py; do
  echo "---- $file ----"
  ast-grep outline "$file" --items all --type method --match 'to|sample|potential|__init__'
done

echo '== Device-related fields and .to() bodies =='
rg -n -A55 -B8 '^\s+def to\(' \
  sbi/inference/posteriors/direct_posterior.py \
  sbi/inference/posteriors/rejection_posterior.py \
  sbi/inference/posteriors/importance_posterior.py \
  sbi/inference/posteriors/mcmc_posterior.py \
  sbi/inference/posteriors/vi_posterior.py \
  sbi/inference/posteriors/vector_field_posterior.py

echo '== VIFakePotential and vector-field constructor context =='
rg -n -A90 -B10 'class FakePotential|class VectorFieldPosterior|def sample\(|def potential\(' \
  tests/vi_test.py \
  sbi/inference/posteriors/vector_field_posterior.py \
  sbi/inference/posteriors/vi_posterior.py

echo '== Other posterior state fields referenced by migration =='
rg -n -C3 '\b(self\.)?(_x|prior|proposal|posterior_estimator|vector_field_estimator|_q|_amortized_q)\b' \
  sbi/inference/posteriors/{direct_posterior,rejection_posterior,importance_posterior,mcmc_posterior,vi_posterior,vector_field_posterior}.py

Length of output: 201030


@BHARATH0153: Not yet. The latest commits address most of Jan’s requests:

  • The VI test now constructs VIPosterior correctly.
  • VIPosterior.__setstate__ now calls the base implementation.
  • Potential-based posteriors and vector_field_estimator are detected.
  • potential_fn.device, distributions, estimators, and _x are reconciled.
  • The stale docstring reference is removed.
  • The PR description no longer mentions the reverted guide update. It also declares AI assistance and local GPU-test execution.

One gap remains for VectorFieldPosterior.

NeuralPosterior.__setstate__ updates self._device, but it does not update VectorFieldPosterior.device. VectorFieldPosterior._sample_via_diffusion() uses self.device to move its time schedule. After loading with map_location="cpu", self.device can still be mps or cuda, while vector_field_estimator is on CPU. Vector-field sampling can then still cause a device mismatch.

The vector-field test only checks _device, potential_fn.device, and estimator parameters. It does not call loaded.sample() or loaded.potential(), so it does not detect this case.

Therefore, this PR does not yet cover all device-related state from #1954. Please synchronize self.device with the reconciled device for posteriors that use it, then execute a vector-field sampling test after the CPU-mapped load.

You are interacting with an AI system.

…eriors

VectorFieldPosterior (and EnsemblePosterior) keep a plain `device`
attribute, read directly during sampling, that the previous restore logic
left on the stale training device. Update it whenever `_device` is
reconciled, and extend the GPU test to assert `loaded.device` and run a
sampling call after loading on cpu.
@BHARATH0153
BHARATH0153 marked this pull request as draft August 4, 2026 13:30
@BHARATH0153 BHARATH0153 closed this Aug 4, 2026
@BHARATH0153 BHARATH0153 reopened this Aug 4, 2026
@BHARATH0153 BHARATH0153 closed this Aug 4, 2026
@BHARATH0153 BHARATH0153 reopened this Aug 4, 2026
@BHARATH0153 BHARATH0153 closed this Aug 4, 2026
@BHARATH0153
BHARATH0153 deleted the fix-stale-device-clean branch August 4, 2026 13:49
@BHARATH0153

BHARATH0153 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor Author

will create new pr with suggested changes

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.

posterior._device goes stale after loading with torch.load(map_location=...)

2 participants