Skip to content

fix: make unconstraining transforms module-owned - #1939

Merged
janfb merged 4 commits into
mainfrom
fix/1893-transform-module
Jul 28, 2026
Merged

janfb merged 4 commits into
mainfrom
fix/1893-transform-module

Conversation

@janfb

@janfb janfb commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1893. Supersedes #1932 and #1933.

Those PRs fixed the problem by handling the transform in two locations, adding complexity and several new functions. Instead, this PR introduces one module that owns the transform for both Zuko and MDNs, including device movement and pickling.

  • let normal module traversal move transform tensors for both MDN and Zuko
  • keep MDN's existing _prior_transform access compatible without estimator-specific pickle hooks
  • pass the batch device when constructing Zuko's unconstraining transform
  • remove the production-only transform tensor collector

Transform tensors remain outside the state_dict, and loading weights still requires reconstructing the estimator through its builder first. The standard sbi save path continues to work.

After main upgraded to PyTorch 2.13, CI exposed that _inv is now a strong reciprocal-transform cache reference. The transform-tree traversal ignores that cache so it detects only structural inverse wrappers; the inverse-orientation and pickle tests cover this behavior.

@codecov

codecov Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.48936% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.80%. Comparing base (3adf008) to head (1bf329f).
⚠️ Report is 4 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/utils/sbiutils.py 89.74% 4 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main    #1939    +/-   ##
========================================
  Coverage   87.80%   87.80%            
========================================
  Files         143      143            
  Lines       13435    13786   +351     
========================================
+ Hits        11796    12105   +309     
- Misses       1639     1681    +42     
Flag Coverage Δ
fast 81.50% <91.48%> (?)

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

Files with missing lines Coverage Δ
...eural_nets/estimators/mixture_density_estimator.py 92.04% <100.00%> (+0.56%) ⬆️
sbi/neural_nets/net_builders/flow.py 96.84% <100.00%> (ø)
sbi/utils/sbiutils.py 88.97% <89.74%> (+3.98%) ⬆️

... and 5 files with indirect coverage changes

@janfb
janfb force-pushed the fix/1893-transform-module branch from 7b6a61d to 7a096f5 Compare July 20, 2026 20:11
@janfb
janfb force-pushed the fix/1893-transform-module branch from 7a096f5 to 1f95b0f Compare July 21, 2026 06:34
@janfb
janfb requested a review from dgedon July 21, 2026 17:34
@janfb janfb mentioned this pull request Jul 22, 2026
8 tasks done
Comment thread tests/inference_on_device_test.py Resolved
Comment thread tests/save_and_load_test.py Resolved
janfb added 2 commits July 28, 2026 09:02
Both call process_device("gpu") but ran under -m "not gpu" on MPS machines,
where the module skipif (CUDA or MPS) and conftest's CUDA-only autoskip
both fail to exclude them.
Transform.__getstate__ clears _inv as a reciprocal cache, but
_InverseTransform stores its wrapped transform there, so pickling a
posterior's theta_transform yielded Inverse(None) and sampling then failed.

Closes #1952. Upstream: pytorch/pytorch#191197.

Also split the transform pickle/dtype test in two, guard _prior_transform
against assignment, and sample from the reloaded posterior in
test_picklability, which previously never used it.
@janfb
janfb merged commit 4a94f9b into main Jul 28, 2026
20 checks passed
@janfb
janfb deleted the fix/1893-transform-module branch July 28, 2026 07:59
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.
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.

transform_to_unconstrained z-scoring is CPU-only (breaks on MPS) and not in state_dict

2 participants