Skip to content

fix: make VIPosterior serialization state-based - #1953

Merged
janfb merged 22 commits into
mainfrom
fix/vi-posterior-trained-on-pickle
Jul 30, 2026
Merged

janfb merged 22 commits into
mainfrom
fix/vi-posterior-trained-on-pickle

Conversation

@janfb

@janfb janfb commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #1939, which fixed the same class of bug for estimator transforms.

VIPosterior stored build functions, __deepcopy__ overrides and parameters/modules
accessors 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 from self and __setstate__ rebuilt them by re-running the
public 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.

  • store how to rebuild q in a _QSpec dataclass, built by _build_q_from_spec; drops
    _q_build_fn, _zuko_flow_type and _q_arg
  • wrap user distributions in AdaptedVariationalDistribution, whose parameters/modules
    are methods on the class; drops adapt_variational_distribution and its two helpers
  • replace make_object_deepcopy_compatible with an explicit detach_and_deepcopy at the
    two 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 path
  • retrain_from_scratch no longer applies the link transform twice, and refuses with a
    clear error when q came in as an already-built distribution, since that says nothing
    about how to build another one
  • find a user TransformedDistribution's parameters on its base distribution, and refuse
    instead 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:

  • LRUEmbedding kept its aggregation as a lambda, so no posterior using that embedding
    net could be pickled at all - including with the default aggregate_fcn="mean"
  • save_and_load_test only checked the shape of the reloaded posterior's samples, which
    is why the _trained_on bug survived: a posterior that silently retrains still returns
    correctly shaped samples. it now compares seeded samples, and checks that saving leaves
    the posterior it saved untouched. also covers ImportanceSamplingPosterior, which had
    no coverage

janfb added 9 commits July 28, 2026 11:30
_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

codecov Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.92035% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.73%. Comparing base (4a94f9b) to head (5bd031a).
⚠️ Report is 3 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/samplers/vi/vi_utils.py 88.52% 7 Missing ⚠️
sbi/neural_nets/embedding_nets/lru.py 88.88% 1 Missing ⚠️
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     
Flag Coverage Δ
fast 82.77% <92.92%> (?)

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.40% <100.00%> (+6.84%) ⬆️
sbi/samplers/vi/vi_divergence_optimizers.py 84.91% <100.00%> (-0.10%) ⬇️
sbi/utils/user_input_checks_utils.py 92.33% <100.00%> (+3.27%) ⬆️
sbi/neural_nets/embedding_nets/lru.py 93.10% <88.88%> (+0.84%) ⬆️
sbi/samplers/vi/vi_utils.py 92.22% <88.52%> (+14.16%) ⬆️

... and 18 files with indirect coverage changes

Comment thread sbi/samplers/vi/vi_utils.py Resolved
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.
janfb added 11 commits July 28, 2026 14:11
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
janfb force-pushed the fix/vi-posterior-trained-on-pickle branch from 929ae5f to 08dbc6e Compare July 30, 2026 11:21
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
janfb merged commit b8ce743 into main Jul 30, 2026
20 checks passed
@janfb
janfb deleted the fix/vi-posterior-trained-on-pickle branch July 30, 2026 12:38
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.

1 participant