Repository navigation
feat: Add AmortizedVIPosterior for amortized variational inference - #1751
Conversation
…ing in training; add gradient flow test
…curacy comparison
…r; update references in implementation and tests
- Reuse Zuko flow enum, - align MAP with potential-based logic, - tighten sampling/validation behavior while updating tests and docs.
- Fix VIPosterior.to() to return self for method chaining (matches AmortizedVIPosterior) - Add theta dimension validation in AmortizedVIPosterior.train() to catch mismatches early - Remove ZukoFlowType from top-level sbi.inference exports (still available via sbi.inference.posteriors) - Update test imports accordingly 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #1751 +/- ##
=======================================
Coverage ? 88.01%
=======================================
Files ? 138
Lines ? 13245
Branches ? 0
=======================================
Hits ? 11658
Misses ? 1587
Partials ? 0
Flags with carried forward coverage won't be shown. Click here to find out more.
|
manuelgloeckler
left a comment
There was a problem hiding this comment.
Hey Jan,
thanks for implementing this. I left a few comments on the tests and __init__ changes.
I wonder if its somewhat easy to connect the old VIPosterior parts with the new AmortizedVIPosterior a bit better. But this would require quite a few changes to the vi parts I think, so also happy to do the amortized VI separately.
Add `build_zuko_vi_flow` function that creates unconditional Zuko normalizing flows for variational inference training. Supports: - NSF (Neural Spline Flow) - MAF (Masked Autoregressive Flow) - Gaussian (full covariance) - Gaussian diagonal Also includes helper `_build_zuko_gaussian_flow` with custom affine transforms (diagonal and lower triangular) for Gaussian variants. This addresses Phase 1, Step 1.1 of the VI unification plan. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Update DivergenceOptimizer to handle both Pyro TransformedDistribution and ZukoUnconditionalFlow variational distributions: - Add VariationalDistribution type alias for Union of flow types - Detect flow type via isinstance check for ZukoUnconditionalFlow - Handle Pyro-specific set_default_validate_args conditionally - Properly register Zuko nn.Module flows in ModuleList Part of VI unification (Phase 2): adapting existing VI infrastructure to work with new Zuko-based flows alongside legacy Pyro flows. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Phase 3 of VI unification: Extend Zuko flow support to all divergence optimizer subclasses (ElboOptimizer, ForwardKLOptimizer, RenyiDivergenceOptimizer). Changes: - Update warmup() to support Zuko flows using sample_and_log_prob - Add clear error for unsupported 'identity' warmup with Zuko flows - Fix missing 'raise' in NotImplementedError for invalid warmup methods - Update _loss() methods to check _is_zuko flag for reparameterized sampling - Refactor elbo_particles() to handle both Zuko and Pyro flow APIs - Fix typo: 'inital_target' -> 'initial_target' 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Fix duplicate __all__ exports in sbi/inference/__init__.py - Remove incorrect ZukoFlowType export from posteriors/__init__.py - Add thread-safety lock to AmortizedVIPosterior.set_x() - Fix missing comma in VIPosterior progress bar display 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Phase 3 Steps 3.1-3.3 of VI unification: - Add _mode tracking attribute for single_x vs amortized modes - Add _build_zuko_flow helper method for building Zuko flows - Update set_q to use Zuko for maf/nsf/mcf/scf flow types - Keep Pyro flows for gaussian/gaussian_diag for backwards compat - Add ZukoUnconditionalFlow validation in set_q - Fix undefined transforms bug in build_zuko_unconditional_flow The train(x_o) signature remains unchanged. DivergenceOptimizer (adapted in Phase 2) handles both Pyro and Zuko flows. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
…rence Add amortized VI support to VIPosterior: - New train_amortized(theta, x) method for training conditional flows q(θ|x) - Updated sample() and log_prob() to handle both single-x and amortized modes - Added _build_conditional_flow() helper using Zuko conditional flows - Mode tracking with warnings when switching between modes - Thread-safety lock for potential_fn state during ELBO computation - Validation-based early stopping for amortized training 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Fix deepcopy/pickle of VIPosterior with _set_x_lock attribute: - __deepcopy__: Create new Lock instead of attempting deepcopy - __getstate__: Pop _set_x_lock from state dict (not picklable) - __setstate__: Restore lock immediately after restoring __dict__ - Update tests for Zuko flow compatibility: - Use sample() instead of rsample() for Zuko flows (which don't have rsample) - Skip .support attribute check for Zuko flows (they don't expose it) - Fix typo in docstring: "due not support" -> "do not support" 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Update VIPosterior.sample() to properly handle batched x in amortized mode - Preserve batch dimension for multi-observation inputs - Squeeze singleton batch dimension to match base posterior behavior - Support default_x via _x_else_default_x() - Implement sample_batched() for amortized mode (delegates to sample()) - Improve log_prob() docstring with batched x documentation - Standardize error types: use ValueError instead of AttributeError - Migrate all tests from AmortizedVIPosterior to VIPosterior.train_amortized() - Update imports and constructor calls - Change .train() to .train_amortized() with flow params - Update assertions for new mode attribute 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Remove AmortizedVIPosterior from __all__ exports in both sbi/inference/__init__.py and sbi/inference/posteriors/__init__.py. All functionality has been migrated to the unified VIPosterior class with its train_amortized() method. Note: The amortized_vi_posterior.py file still exists pending manual deletion approval. The vi_pyro_flows.py file is retained as it's still needed for gaussian/gaussian_diag flow types. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
|
Thanks for the review @manuelgloeckler! As discussed offline, I made major updates to this PR to combine both single-x VI and amortized VI into one posterior class. AI Usage: As I am experimenting with different AI coding strategies at the moment, I tried setting up a detailed "product requirement file" summarizing our goal and then set up Claude Code in a loop (similar to the RALPH setting) that runs over night and works on one step at at time, does a self-review, writes the progress into a file and then starts from scratch again with new context. Therefore, there are many commits co-authored by Claude. It worked reasonably well, but not perfect. Claude failed fixing an issue SummaryUnified APIInstead of a separate AmortizedVIPosterior class, we now have a single VIPosterior with two training modes:
# Single-x mode (unchanged)
posterior = VIPosterior(potential_fn, prior)
posterior.train()
samples = posterior.sample((1000,))
# Amortized mode
posterior = VIPosterior(potential_fn, prior)
posterior.train_amortized(theta, x, flow_type=ZukoFlowType.NSF)
samples = posterior.sample((1000,), x=x_new) # works for any xI agree to your points on the tests:
|
617d5a4 to
8b48387
Compare
Resolved conflicts: - vi_posterior.py: Combined docstrings for sample() Args - vi_test.py: Kept sampling_method parameterization for comprehensive testing - vi_test.py: Removed duplicate assertion for K parameter 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
| from torch import Tensor | ||
| from torch.distributions import Distribution | ||
|
|
||
| from sbi.samplers.vi.vi_utils import move_all_tensor_to_device |
There was a problem hiding this comment.
One can think about moving this helper to general utils, if now used quite frequently.
Kinda was more a "brute-force" approach for non modules like Pyro distributions (but that also applies for priors). While it is quite general there are a few special cases where I think this can fail (i.e. whatever is not accounted in the base_recursor). Although, it might also moves "to much" to device.
There was a problem hiding this comment.
agreed, moved to torchutils. additionally, I changed to using prior.to() on the priors that have internally been processed (process_prior) so that they have to().
manuelgloeckler
left a comment
There was a problem hiding this comment.
Thanks. This looks great!
Love that the amortized and non-amortized methods now share the same VIPosterior!
It worked reasonably well, but not perfect. Claude failed fixing an issue zuko has in 1D cases: it resorts to a element-wise transform and performs much worse than pyro.
Not entirely sure about that (and what is happening there to affect performance). The pyro gaussian where also implemented as transforms, no? But I can imagine that some broadcasting breaks.
But its anyway a bit artificial to implement the Gaussians via Normalizing Flows so I think its totally fine to use the custom Gaussian implementation. Although I would the remove the Zuko related implementations (as I think they anyway cannot be used right now).
Another point is that I think it would be could to either do an How to guide on VI/Amortized VI (or 'tutorial' notebook). I think currently it is only mentioned 'implemented methods'. But this can also be "future issue" i.e. also related to #1721
|
I ran the slow tests locally and a few tests do fail: FAILED tests/vi_test.py::test_c2st_vi_external_distributions_on_Gaussian[1] - TypeError: torch.distributions.transformed_distribution.TransformedDistrib...
FAILED tests/vi_test.py::test_c2st_vi_external_distributions_on_Gaussian[2] - TypeError: torch.distributions.transformed_distribution.TransformedDistrib...
FAILED tests/vi_test.py::test_amortized_vi_accuracy[nle] - AttributeError: 'MultivariateNormal' object has no attribute 'to'
FAILED tests/vi_test.py::test_amortized_vi_accuracy[nre] - AttributeError: 'MultivariateNormal' object has no attribute 'to'
FAILED tests/vi_test.py::test_amortized_vi_batched_sampling - AttributeError: 'MultivariateNormal' object has no attribute 'to'
FAILED tests/vi_test.py::test_amortized_vi_log_prob - AttributeError: 'MultivariateNormal' object has no attribute 'to'
FAILED tests/vi_test.py::test_amortized_vi_default_x - AttributeError: 'MultivariateNormal' object has no attribute 'to'
FAILED tests/vi_test.py::test_amortized_vi_map - AttributeError: 'MultivariateNormal' object has no attribute 'to'The later is due to: def to(self, device: Union[str, torch.device]) -> None:
"""
Move likelihood_estimator, prior and x_o to the given device.
It also set the device attribute to the given device.
Args:
device: Device to move the likelihood_estimator, prior and x_o to.
"""
self.device = device
self.likelihood_estimator.to(device)
> self.prior.to(device) # type: ignore
^^^^^^^^^^^^^
E AttributeError: 'MultivariateNormal' object has no attribute 'to'i.e. I think the The first two I am not sure about. In the previous version one could pass non-module distribution which where wrapped into a Not sure we either remove this functionality or reintroduce that. |
- add helper to move dist to device - remove unused tensor device helper
| a `VIPosterior`, then the arguments will be copied from it (relevant | ||
| for multi-round training). | ||
|
|
||
| Note: For 1D parameter spaces, normalizing flows may be unstable. |
There was a problem hiding this comment.
Not sure if we should generally recommend gaussian for 1d (are all the flows unstable in 1d?)
in zuko, even the NSF and coupling flows do not perform well in 1D. I added the Gaussianization Flow as option, which gives a MoG and will likely work better than a plain learned Gaussian. especially in 1D multimodal settings. |
The IW objective lived in a method named loss_rsample, which only worked as an override of a parent method with the same name. When sbi-dev#1751 renamed the parent method, the override was orphaned and IW silently trained the plain ELBO. The IWELBO is now computed in _loss itself, the entry point every optimizer overrides. The test now checks the displayed loss against a closed form (K equal log-weights c give c) instead of restating the implementation, and no longer pins how particles are requested.
* fix(vi): dispatch IW optimizer to IWELBO loss * fix(vi): report IWELBO loss in log space * refactor(vi): compute the IWELBO in _loss directly The IW objective lived in a method named loss_rsample, which only worked as an override of a parent method with the same name. When #1751 renamed the parent method, the override was orphaned and IW silently trained the plain ELBO. The IWELBO is now computed in _loss itself, the entry point every optimizer overrides. The test now checks the displayed loss against a closed form (K equal log-weights c give c) instead of restating the implementation, and no longer pins how particles are requested. * fix(vi): detach log q whenever DReG is on, also after update DReG needs the squared importance weights together with a log q whose parameters are detached. The IW and alpha optimizers set stick_the_landing once in __init__, but a second train() call changes dreg through update() without touching stick_the_landing. So train() followed by train(dreg=True) squared the weights with an attached log q (biased gradient), and dreg=True followed by dreg=False kept the detachment on. The ELBO optimizer now asks _detach_log_q() on every step, and the IW and alpha optimizers answer from both flags. The IW docstring now recommends dreg instead of stick_the_landing, which alone is biased for the IWELBO (Tucker et al., 2018). The new test checks that switching dreg through update() gives the gradient of a newly built optimizer. --------- Co-authored-by: Jan <[email protected]>
Summary
This PR implements amortized variational inference via a new
AmortizedVIPosteriorclass, addressing #909.Note on AI usage: I used Claude Code to help implementing this. I did many iterations and careful reviewing myself and with a very critical Codex 5.2 reviewer.
Context
The existing
VIPosteriortrains an unconditional variational distributionq(θ)for a fixed observationx_o. This requires retraining for every new observation, which is inefficient in scenarios requiring inference across many observations.Amortized VI addresses this by learning a conditional distribution
q(θ|x)that generalizes across observations. Once trained on simulation data(θ, x), the posterior can provide instant samples for any newxwithout retraining.As part of this PR, we also align MAP estimation with the base posterior logic (potential-based) and keep sampling output shapes consistent across posteriors.
Implementation
We introduce
AmortizedVIPosterior, which trains a conditional normalizing flowq(θ|x)by optimizing the ELBO against a potential function from NLE/NRE:A
ZukoFlowTypeenum provides type-safe selection of flow architectures (NSF, MAF, NAF, UNAF, SOSPF, NICE, GF, NCSF, BPF).Design Choices
Separate class vs extending VIPosterior
We created a new class rather than adding an amortized mode to
VIPosterior:train()vstrain(theta, x))VIPosteriorZukoFlowType enum scoping
The
ZukoFlowTypeenum is defined insbi.neural_nets.factoryand reused here:log_prob(NSF, MAF, NAF, UNAF, SOSPF, NICE, GF, NCSF, BPF)Potential function interface
The implementation uses the existing
potential_fn.set_x()pattern for efficiency. This makes the class non-thread-safe, which is documented in the class docstring.Testing
We validate correctness using a linear Gaussian problem where the true posterior is
analytically known. Tests verify:
VIPosterioron the same problemx, untrained model)Closes #909