Repository navigation
fix: unify device handling and run the GPU test suite on MPS - #1958
Merged
Merged
Conversation
tests/conftest.py keyed the autoskip for gpu-marked tests on
torch.cuda.is_available(), while the module guard in
inference_on_device_test.py and process_device("gpu") both count CUDA or
MPS. The two gates disagreed, so on Apple silicon every gpu-marked test
was skipped even though the tests themselves are device-agnostic: they
resolve the device via process_device and compare device types.
Use gpu_available() so collection and device resolution cannot diverge.
This makes 244 GPU tests executable on MPS.
Both tests parametrized the literal "cuda", which process_device cannot resolve on a machine whose GPU is MPS. Parametrize "gpu" and let process_device pick the backend, comparing device types rather than full device strings. In vf_estimator_test.py the gpu marker also sat on the test function, so its cpu parametrization was skipped along with the GPU one and never ran in the non-GPU selection. Move the marker onto the gpu param.
process_device set PYTORCH_ENABLE_MPS_FALLBACK=1 when selecting MPS, but PyTorch registers that fallback when torch is imported, so setting it afterwards has no effect. sbi therefore advertised a CPU fallback for operators MPS does not implement (aten::binomial, aten::_linalg_eigh.eigenvalues) that was never active, and users saw a NotImplementedError instead. Warn and point at the environment variable, which users must set before importing torch, rather than silently doing nothing.
PyTorch does not implement aten::binomial or aten::_linalg_eigh.eigenvalues for MPS, which made test_mnle_on_device, test_analysis_modules[gpu] and the Gaussian iid methods of test_vector_field_methods_degvice_handling fail there. All three pass when PYTORCH_ENABLE_MPS_FALLBACK=1 is set before torch is imported, so skip on the missing operator rather than on the backend. skip_if_mps_op_unsupported names the operator in the skip reason and tells the reader how to run the test anyway. For the vector field test only the eigh-dependent iid methods are dropped, keeping the ode/sde and log_prob device coverage, and the reduced coverage is warned about.
test_run_tarp_correct_on_cuda_device asserted that torch.histogram raises NotImplementedError, as a tripwire for pytorch#69519 being fixed. That gap is CUDA-only; MPS implements torch.histogram, so the assertion failed with DID NOT RAISE there. Guard the tripwire on dev.type == "cuda" and rename the test, since it runs on whichever GPU backend is available.
TabPFNFlow stores its context on CPU because TabPFN's fit/predict API consumes CPU arrays, and _autoregressive_log_prob/_autoregressive_sample already worked in that space: joint_data comes from the CPU context and per-dimension results are moved to CPU before accumulation. Their arguments, however, arrived on the module's device, since _embed_condition runs the embedding net. Concatenating the two raised "Passed CPU tensor to MPS op" in log_prob on a GPU posterior. Move those arguments to CPU at the boundary. The public methods already return results on the caller's device, so nothing changes for callers. test_npe_pfn_on_device could not catch this: it asserted on posterior.estimator, which DirectPosterior does not have, and it built a GPU prior while passing device="cpu", which trips sbi's prior/training device check before reaching the estimator. Fix both so the test covers what its docstring describes.
The warning only covered device="gpu", but the GPU how-to tells users to pass device="mps" directly, which took the custom-device branch and got no advice at all. Warn for any MPS device, and expose mps_fallback_enabled() so tests can key skips on the same predicate instead of re-parsing the variable. Parse it like PyTorch does, i.e. any non-zero value counts. Document the import-time constraint in the GPU how-to, since sbi can only report it, not fix it.
Same defect as vf_estimator_test.py: the gpu marker sat on the function while the parametrization covered cpu and gpu, so the cpu case was skipped on every machine without a GPU and never ran in CI.
Two follow-ups from review: The context assertion in test_npe_pfn_on_device cannot fail, because set_context_flat moves the context to CPU unconditionally. The observable invariant is that samples and log_prob come back on the queried device, which is what the TabPFN CPU round-trip has to preserve and what a regression would break. Assert that too. In tabpfn_flow.py, only input_flat ever arrived on a foreign device; _embed_condition already returns CPU conditions, so moving condition_flat was a no-op that implied a bug where there was none. Also stop warning about the reduced iid coverage when num_trials == 1, where no iid method runs at all.
The MPS check in the custom-device branch assumed a string, but process_device(None) is a valid call: BoxUniform passes device=None through, and check_device(None) resolves to torch's default device. Guard with str(device).
process_device had two contracts. "gpu" was resolved to an indexed device
string and configured torch for it; every explicit spelling was returned
verbatim after a validity check only. Two bugs followed.
Passing device="mps" raised "Cannot convert a MPS Tensor to float64
dtype" whenever torch's default dtype was float64, because only the
"gpu" path lowered it to float32 before allocating the probe tensor. The
GPU how-to recommends device="mps", and tests/conftest.py pins float32,
so nothing caught it.
Passing "mps" or "cuda" also skipped index normalization, and sbi
compares device strings in three places. "mps" against a tensor's
"mps:0" made validate_theta_and_x warn and copy on every
append_simulations, and made move_all_tensor_to_device refuse a leaf
tensor that was already on the target device.
Resolve the device first, then apply the MPS and CUDA handling once,
whichever way it was spelled. canonical_device() adds the explicit index
that string comparisons need, since torch.device("cuda") and
torch.device("cuda:0") are not equal, and the three comparison sites use
it. BoxUniform.to() now stores the resolved device rather than its
argument.
Behavior changes: process_device returns "cuda:{index}" for "cuda" and
"mps:0" for "mps", None maps to "cpu" instead of being passed through,
torch.cuda.set_device is called for explicit CUDA devices too, and an
uninterpretable device raises a helpful RuntimeError.
tests/prior_device_tests.py matched neither test_*.py nor *_test.py, so pytest never collected it and its ten prior-device tests had never run. Rename it, and skip the two that sample from a Binomial when MPS cannot. They assert prior.device == device after .to(), which is exactly the invariant the device canonicalization restores.
Four follow-ups, all in the device resolution path:
Drop the torch.cuda.set_device call. Before this branch it was a no-op,
since the only path reaching it had just read the current device index;
extending it to explicit devices made a constructor mutate process-global
CUDA state, and made the meaning of device="cuda" depend on the
construction order of unrelated sbi objects. Nothing in sbi reads the
current device: every allocation passes a resolved device string.
Canonicalize before the "cpu" shortcut. torch.device("cpu") == "cpu" is
False, so that spelling skipped the shortcut and reached check_device,
whose torch.randn draw perturbs seeded runs. "cpu:0" now also collapses
to "cpu", so it compares equal to a CPU tensor's device.
Keep the index when BoxUniform infers its device from low: low.device.type
turned cuda:1 into "cuda", which canonical_device then resolves to the
current device, silently relocating the prior.
Warn about the missing MPS fallback once per process. It fires from
process_device, so every prior, trainer and posterior added another copy
of advice that is about the environment, not the call site.
Also test canonical_device directly. It is a pure function that needs no
GPU, so unlike the rest of the MPS work it can run on CPU-only CI.
Each .to() stored its raw argument in the public self.device while
super().__init__ resolved the same argument into self._device, so
posterior.to("mps") left the two disagreeing, and passing a torch.device
left self.device as an object that user code cannot .split(":").
posterior.to("gpu") raised outright: __init__ accepts the alias but .to()
forwarded it to torch, which rejects it. No test caught this because they
all call process_device before passing a device in.
Resolve first, like BoxUniform.to already does.
Two sites outside torchutils matched device strings literally, which breaks now that sbi hands out indexed strings everywhere. nn_utils.check_net_device compared str(param.device) to str(device); its callers all pass "cpu" today, so this is consistency rather than a fix. LC2ST is user-facing: it compared self.device.lower() to "cuda" and "mps", so a device string copied from trainer._device or posterior.device, e.g. "mps:0", silently fell back to the CPU MLPClassifier without even the warning that a bare "mps" would trigger.
Renaming the file made pytest collect it, but the gpu marker still sat on the three test functions, and every CI job filters -m "not gpu". So all ten parametrizations stayed deselected and my previous claim that they now run in CI was wrong. Move the marker onto the gpu param, as the other tests in this branch do: five cpu parametrizations now actually run.
process_device(None) now returns "cpu" instead of passing None through, so resolving the None parametrization turned BoxUniform's device inference into an explicit CPU device. With tensors on the GPU that put the prior on the CPU while training ran on the GPU, tripping check_if_prior_on_device. Only pass a device through process_device when there is one.
BasePotential.__init__ and .to() stored the device argument verbatim, so
potential.to('gpu') handed the alias straight to torch and raised, and
explicit spellings ('cuda' vs 'cuda:0') survived as unequal strings. One
process_device call in the base class covers the likelihood, posterior,
ratio, and custom-wrapper potentials; VectorFieldBasedPotential overrides
.to() and needs its own. EnsemblePotential was already fixed.
VIPosterior.__init__ ran the base class (which resolves the device via
process_device) and then overwrote self._device with the raw argument;
.to() stored the raw argument as well. VIPosterior(..., device='gpu') and
.to('gpu') therefore crashed once the string reached torch, and explicit
spellings broke later string comparisons. The eighth posterior to get the
fix the other seven received.
The .to() methods of PytorchReturnTypeWrapper, MultipleIndependent, and OneDimPriorWrapper stored the raw device argument, degrading the resolved device their constructors establish. RestrictedPrior never resolved its device at all, so device='gpu' crashed at the first allocation. The new tests pass 'cpu:0' so the stored-device invariant is checked without a GPU.
The device-type comparison introduced on this branch fed self.device to torch.device(), which raises for sbi's 'gpu' alias where main silently fell back to the CPU classifier. Parse leniently: valid torch devices get the index-robust comparison, anything else keeps the documented warn-and-use-CPU behavior.
test_process_device expected cuda:{current_device} even for the explicit
'cuda:0' input, which fails on a multi-GPU machine whose current device
is not 0. And one .strip(':0') survived in inference_on_device_test.py;
it corrupts any index other than 0 ('cuda:10' -> 'cuda:1').
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #1958 +/- ##
==========================================
+ Coverage 87.93% 88.03% +0.09%
==========================================
Files 143 143
Lines 13471 14255 +784
==========================================
+ Hits 11846 12549 +703
- Misses 1625 1706 +81
Flags with carried forward coverage won't be shown. Click here to find out more.
|
canonical_device and process_device raise the same error from the same line, so one reject test covers both. Drop the comments that restated the docstrings.
janfb
added a commit
that referenced
this pull request
Jul 30, 2026
VIPosterior.to() and DivergenceOptimizer.to() only move q when it offers to(). The wrapper hid a module-backed q's own to(), so moving such a posterior to another device left the variational parameters behind and training crashed with a device mismatch. Found by review against main, where the unwrapped module moved fine. The wrapper now moves the tensors it knows about in place, so that the optimizer and the wrapped distribution keep seeing the same objects. Complements #1958, which resolves device spellings but does not touch how q is moved.
janfb
added a commit
that referenced
this pull request
Jul 30, 2026
* refactor(vi): replace q build closures with a serializable spec _q_build_fn stored a lambda on the instance, so pickling had to strip it and __setstate__ had to re-run the public set_q to rebuild it. _QSpec holds data only and _build_q_from_spec is a method, so both survive pickling untouched. Subsumes _zuko_flow_type and _q_arg. Also fixes retrain_from_scratch for a user Callable q, which called the builder with no arguments. * fix(vi): make custom-Distribution q picklable adapt_variational_distribution attached parameters()/modules() as per-instance closures, so a posterior with a user Distribution could not be pickled at all, and retrain_from_scratch lost them through deepcopy. AdaptedVariationalDistribution exposes them as real methods. It also honours user-supplied parameters for a TransformedDistribution input, which the old `parameters == [] or modules_fn == []` check always skipped. * fix(vi): stop pickling from mutating the posterior it serializes __getstate__ nulled _optimizer, _q_build_fn and the injected __deepcopy__ hooks on self before copying __dict__, so pickle.dumps damaged the live object: retrain_from_scratch then failed on the original and optimizer state was lost. __setstate__ repaired only the copy, via the public set_q, which also cleared _trained_on so a reloaded posterior refused to sample. __getstate__ now copies first and nulls _optimizer in the copy; __setstate__ is a plain assignment. make_object_deepcopy_compatible injected an unpicklable closure that captured its object by reference, so copies inherited a hook bound to the original and the optimizer stepped a different q than sample() read; it is replaced by an explicit detach_and_deepcopy at the two call sites that need it. Deleting __deepcopy__ lets deepcopy and pickle share one path. deepcopy of a trained posterior no longer carries _optimizer over; train() rebuilds it on demand. * test(vi): cover serialization through the public API Existing tests sampled `_q` directly and never trained, so they could not see any of the serialization damage. They now train first and go through sample(). Adds coverage for: dumps not mutating the original, retrain_from_scratch after a round trip, a custom-Distribution q, deepcopy keeping optimizer/q identity, and amortized mode, which had none. Removes the VIPosterior skip in test_picklability added by #1939. * docs(vi): document retrain_from_scratch semantics per q kind Flows and Callable builders re-initialise fresh; a user Distribution returns to the snapshot taken when q was set, since sbi cannot re-randomize an opaque object. Adds a test pinning all three so the asymmetry cannot drift. * test(vi): consolidate the serialization suite Drops the trained-posterior checks appended to test_pickle_support and test_deepcopy_support, which are parametrized over eight flows and so ran ~24 redundant trainings for a flow-independent bug; those tests go back to being cheap smoke coverage. The dedicated tests now share one fixture and parametrize over the four ways of specifying q, which also adds the Callable and multi-round paths that were previously untested. * fix(vi): keep retrain_from_scratch correct for adapted and instance q Two gaps found in review, both reproducible: The retrain path assigns through the public q setter, which re-wrapped an already-adapted Distribution in a second AdaptedVariationalDistribution. Since the support comparison is not idempotent, link_transform was applied twice and sampling then failed its support check for any prior with bounded support. The quality-control retry calls retrain_from_scratch automatically, so this was not opt-in. set_q now leaves an already-adapted q alone. The _flow_types branch kept an existing spec so repeated retrains would work, but that also silently preserved a stale recipe when an external caller passed a hand-built instance, rebuilding the wrong family. It now always records kind="instance"; train() preserves its own spec across the setter instead. Tests use a Gamma prior, since with an identity link transform double-wrapping is a no-op and cannot be observed. * style(vi): let the code carry the explanation Drops inline comments and docstring paragraphs that recounted why each bug existed; that history belongs in these commits, not in the source. What remains are constraints a future editor needs: that _QSpec must stay data-only, that AdaptedVariationalDistribution must not grow `to`, `sample_and_log_prob` or an nn.Module base, that __getstate__ must null in the copy, and why the bounded- prior test needs a Gamma prior. * style(vi): use plain sbi wording in comments and docstrings Replaces pickle-protocol jargon ("pickles by value/by reference", "null the copy", "mirror the surface") and the invented "recipe" metaphor with the vocabulary the rest of sbi uses. The serialization dunders now open with the same phrasing as their counterparts in base_posterior.py. * refactor(vi): trim the user-distribution wrapper Addresses review: the wrapper walked a TransformedDistribution's base and transforms to discover parameters, which was the least covered code in the PR and only reachable for a q that supplies none. It now uses the given tensors, or delegates to the distribution's own parameters(), and raises up front when there are neither instead of handing the optimizer an empty list. That leaves get_parameters and get_modules unused, so both are removed; they were internal and not exported. vi_utils.py drops 47 lines and coverage of it rises from 83% to 90%. Also cuts the _QSpec docstring paragraph and rewords the two unclear comments in set_q. * fix(vi): find parameters on a TransformedDistribution's base Review caught that trimming the wrapper narrowed one input: a TransformedDistribution whose base distribution exposes parameters() used to work without an explicit parameters= argument, and started raising instead. The wrapper now falls back to the base distribution, so that case keeps working while anything more exotic still asks for parameters= explicitly. The error is unchanged when there really are no trainable tensors. * test(vi): cover more with fewer tests The TransformedDistribution case becomes a fifth q kind in the shared fixture, so the parametrized round-trip test exercises it through pickling rather than a standalone test only checking construction. The bounded-prior and amortized tests build through the fixture too. The semantics test now covers one representative per side of the asymmetry instead of every kind: the round-trip test already covers all five, and this one only distinguishes fresh weights from a restored snapshot. Net 20 fewer lines and 5 fewer training runs, with the TransformedDistribution path gaining pickle coverage it did not have. * test(vi): reach the TransformedDistribution q kind A stray inner condition made the transformed parametrization build a gaussian q, so the base-distribution lookup had no coverage. * fix(vi): refuse parameters sbi cannot see Dropping the recursive transform scan meant trainable tensors held by a transform were silently left out of training. Ask for them instead. * fix(vi): also look inside composed transforms Torch keeps a ComposeTransform as a single entry in q.transforms, so the flat check missed anything nested in one. * fix(nets): make LRUEmbedding picklable Both aggregation presets were lambdas, so no posterior using this embedding net could be saved, including with the default "mean". Also names the valid presets in the error for an unknown one. * test: assert pickling round-trips posteriors, not just their shapes Comparing seeded samples catches a lost weight or a silently retrained VIPosterior, which a shape assertion cannot. Also checks the saved posterior itself is untouched, and covers ImportanceSamplingPosterior. * fix(vi): let device moves reach an adapted q VIPosterior.to() and DivergenceOptimizer.to() only move q when it offers to(). The wrapper hid a module-backed q's own to(), so moving such a posterior to another device left the variational parameters behind and training crashed with a device mismatch. Found by review against main, where the unwrapped module moved fine. The wrapper now moves the tensors it knows about in place, so that the optimizer and the wrapped distribution keep seeing the same objects. Complements #1958, which resolves device spellings but does not touch how q is moved. * docs(vi): note builders must be module-level; unshare copied q spec Review follow-ups: a lambda passed as a q builder only fails at pickling time with an opaque error, so say so where the Callable is documented. And give a posterior built from another one its own _QSpec, so the two cannot cross-contaminate if the spec is ever mutated in place. * fix(vi): also move auto-detected parameters across devices The wrapper's to() only moved explicitly passed parameters and a source with its own to(). Parameters auto-detected from a plain-distribution base were left behind - a gap review caught in the previous fix, though main never moved these either. Now every shape the wrapper serves moves: the source and modules first, since torch handles meta there, then the remaining tensors in place via .data. The device test now covers all three wrapper shapes. Plain tensors move by .data reassignment, which the meta device refuses, so those two kinds run on real hardware (mps or cuda) and skip on cpu-only machines. * fix: construct OneDimPriorWrapper regardless of global validation The wrapper forwarded the wrapped prior's live validation flag to Distribution.__init__ before setting self.prior, so torch's validation read the arg_constraints property on a half-built object. Whether this crashed depended on global state: MultipleIndependent(validate_args=True) turns validation on process-wide, and this PR's added tests reshuffled the CI shards so exactly that ordering hit test_prior_wrappers. Set self.prior first and skip validation on the wrapper itself - it only delegates, and the wrapped prior validates its own arguments. Setting self.prior first alone is not enough: torch would then look for the delegated rate parameter on the wrapper. The MultipleIndependent global side effect deserves its own issue. * test(vi): consolidate the serialization tests Review question: does the suite need all these lines? No. The old per-family pickle and deepcopy tests checked untrained posteriors through the private _q, and deepcopy now shares the pickle path, so one seeded per-family compare covers both. The no-mutation checks move into the round-trip test, which widens them from one q kind to all five. The per-kind retrain semantics test only pinned documented behavior, so it goes. tests/vi_test.py shrinks by 80 lines with the same guards.
janfb
pushed a commit
that referenced
this pull request
Jul 31, 2026
Brings main in through the stack. Conflict notes: - OneDimPriorWrapper: main fixed the same bug in #1958 by hardcoding validate_args=False, which silently ignores the caller. This branch honours it and returns no arg_constraints, which is what makes that safe. Note the validate_args= line itself auto-merged in main's favour with no conflict marker, leaving arg_constraints -> {} as dead code, so it needed fixing by hand. - torchutils: kept set_validate_args alongside main's rewritten process_device. - user_input_checks: kept both canonical_device and set_validate_args. - test_one_dim_wrapper_constructs_with_validation_on: kept, and it now asserts the setting is actually honoured rather than only that construction succeeds.
5 of 7 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
tests/conftest.pyskipped GPU tests unless CUDA was available. The rest of sbi accepts CUDA or MPS. Because of this mismatch, all ~250 GPU tests were silently skipped on Apple silicon. sbi has no GPU CI job, so nobody saw it.We enabled the tests on MPS. They found real bugs in the device handling. This PR fixes them.
What this PR does
One contract for all device spellings
process_devicehad two contracts."gpu"got resolved and configured. Explicit spellings were returned as-is after a validity check."gpu""mps:0", float32 default set"mps:0", float32 default set"mps"TypeErrorunder float64 default"mps:0", float32 default set"cuda""cuda""cuda:0"NoneNone"cpu""bogus"RuntimeError("Could not interpret ...")Two bugs followed from the old behavior:
device="mps"crashed when the default dtype was float64. Only the"gpu"path set float32. Our docs recommenddevice="mps"."mps"and"mps:0"name the same device but are not equal as strings. This caused false warnings, needless copies, and a silent CPU fallback inLC2ST.The new
canonical_device()returns each device string with an explicit index. All comparison sites use it..to(device)resolves its argumentThe
.to()methods stored the raw argument..to("gpu")crashed..to("mps")made.deviceand._devicedisagree. This affected all eight posterior classes, the potential classes, three prior wrappers, andRestrictedPrior.VIPosterior.__init__even overwrote the resolved device with the raw argument. All of them now resolve throughprocess_device.PYTORCH_ENABLE_MPS_FALLBACKwas set too late to workPyTorch reads this variable at
import torch. sbi set it afterwards, so it never had an effect. Users gotNotImplementedErrorfor operators that MPS lacks. sbi now warns once per process and names the fix. The GPU how-to documents it.TabPFN
log_probfailed on every GPU_autoregressive_log_probconcatenated the caller's tensor with the always-CPU TabPFN context. One.to("cpu")was missing. This bug was not MPS-specific.Test fixes
prior_device_tests.pydid not match the pytest file pattern. It was never collected. Renamed toprior_device_test.py.@pytest.mark.gpuon the function while parametrizing["cpu", "gpu"]. Their cpu cases never ran in CI. The marker moved to the gpu param."cuda"instead of asking for"gpu"."cpu:0", which must be stored as"cpu". This checks the stored-device invariant on CPU-only CI.Behavior changes
process_device("cuda")returns"cuda:0".process_device("mps")returns"mps:0".process_device(None)returns"cpu", notNone.RuntimeError("Could not interpret ...")."cuda:0"where they recorded"cuda". The load path does not parse this string, so loading is unaffected (seeposterior._devicegoes stale after loading withtorch.load(map_location=...)#1954 for the separate stale-_deviceissue).Validation
-m "not slow and not gpu": 6279 tests, 0 failed.-m gpuon MPS (-n auto,PYTORCH_ENABLE_MPS_FALLBACK=1): 253 tests, 186 passed, 1 skipped, 66 xfailed, 0 failed. Before this branch, 0 of these tests ran on MPS.ruff check,ruff format,pyright sbi: clean."cuda"index resolution, and the removedtorch.cuda.set_deviceno-op.Developed with AI assistance (Claude Code), including three adversarial review passes. All findings are folded into the commits.