Repository navigation
fix: reconcile posterior._device after torch.load with map_location - #1959
BHARATH0153 wants to merge 12 commits into
Conversation
d49b99c to
c50e4d8
Compare
Codecov Report❌ Patch coverage is
❌ 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
Flags with carried forward coverage won't be shown. Click here to find out more.
|
c50e4d8 to
3785286
Compare
3785286 to
2a3f8b6
Compare
|
@janfb once look into these when you are free thanks! |
|
Thanks for taking this on @BHARATH0153 . Overall, 1. The VI test has never run.
Please always run gpu-marked tests on your machine before you push. CI cannot catch these failures. 2. The fix cannot reach
3. The fix does nothing for the potential-based posteriors. The potential classes are not 4. For
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 5. Small points.
|
|
One more point @BHARATH0153 , separate from the review above. I want to share a few habits that 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.
None of this is meant to slow you down. The opposite: when a PR comes with the 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.
|
Important Review skippedDraft detected. 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:
📝 WalkthroughWalkthroughThe 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. ChangesPosterior device reconciliation
Estimated code review effort: 3 (Moderate) | ~20 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
sbi/inference/posteriors/base_posterior.pysbi/inference/posteriors/vi_posterior.pysbi/utils/torchutils.pytests/inference_on_device_test.py
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.
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.
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.
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
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.pyLength 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.pyLength 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 --commentsLength of output: 143922
Completed:
Still unresolved:
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. |
|
Tip For best results, initiate chat on the files or code changes.
Completed items include:
The remaining required changes are:
Please address these points before requesting approval. 🐇 You are interacting with an AI system. |
|
Tip For best results, initiate chat on the files or code changes.
Remaining items:
Please address these items and add the end-to-end mapped-load assertions before requesting approval. You are interacting with an AI system. |
|
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.pyLength 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.pyLength of output: 42288
One gap remains for
ts = ts.to(self.device)After The vector-field test also only checks attributes. It does not call You are interacting with an AI system. |
|
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}.pyLength of output: 201030
One gap remains for
The vector-field test only checks Therefore, this PR does not yet cover all device-related state from 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.
|
will create new pr with suggested changes |
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