Repository navigation
fix: make VIPosterior serialization state-based - #1953
Merged
Merged
Conversation
_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.
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.
__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.
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.
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.
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.
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.
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.
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.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #1953 +/- ##
==========================================
- Coverage 87.93% 87.73% -0.21%
==========================================
Files 143 143
Lines 13471 15426 +1955
==========================================
+ Hits 11846 13534 +1688
- Misses 1625 1892 +267
Flags with carried forward coverage won't be shown. Click here to find out more.
|
janfb
commented
Jul 28, 2026
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.
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.
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.
A stray inner condition made the transformed parametrization build a gaussian q, so the base-distribution lookup had no coverage.
Dropping the recursive transform scan meant trainable tensors held by a transform were silently left out of training. Ask for them instead.
Torch keeps a ComposeTransform as a single entry in q.transforms, so the flat check missed anything nested in one.
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.
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.
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.
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.
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.
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.
janfb
force-pushed
the
fix/vi-posterior-trained-on-pickle
branch
from
July 30, 2026 11:21
929ae5f to
08dbc6e
Compare
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.
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.
Follow-up to #1939, which fixed the same class of bug for estimator transforms.
VIPosteriorstored build functions,__deepcopy__overrides andparameters/modulesaccessors as instance attributes. When these are functions, they cannot be pickled and need to be handled extra in
__get_state__, causing a lot of trouble in recent PRs:__getstate__stripped them fromselfand__setstate__rebuilt them by re-running thepublic
set_q.When reviewing the current state thoroughly, I discovered a lot of implicit bugs that where not covered in the tests.
This PR changes this approach with class-level methods, so the serialization hooks become as trivial as every other
posterior's.
qin a_QSpecdataclass, built by_build_q_from_spec; drops_q_build_fn,_zuko_flow_typeand_q_argAdaptedVariationalDistribution, whoseparameters/modulesare methods on the class; drops
adapt_variational_distributionand its two helpersmake_object_deepcopy_compatiblewith an explicitdetach_and_deepcopyat thetwo call sites that need it
__getstate__clears entries on the copy,__setstate__is a plain assignment, and__deepcopy__is gone so deepcopy and pickle share one pathretrain_from_scratchno longer applies the link transform twice, and refuses with aclear error when
qcame in as an already-built distribution, since that says nothingabout how to build another one
TransformedDistribution's parameters on its base distribution, and refuseinstead of silently leaving out tensors that sit in its transforms
Two things outside VI, same bug class, found while checking where else we store functions
on instances:
LRUEmbeddingkept its aggregation as a lambda, so no posterior using that embeddingnet could be pickled at all - including with the default
aggregate_fcn="mean"save_and_load_testonly checked the shape of the reloaded posterior's samples, whichis why the
_trained_onbug survived: a posterior that silently retrains still returnscorrectly shaped samples. it now compares seeded samples, and checks that saving leaves
the posterior it saved untouched. also covers
ImportanceSamplingPosterior, which hadno coverage