Skip to content

feat: Add AmortizedVIPosterior for amortized variational inference - #1751

Merged
janfb merged 33 commits into
mainfrom
add-amortized-vip
Feb 16, 2026
Merged

janfb merged 33 commits into
mainfrom
add-amortized-vip

Conversation

@janfb

@janfb janfb commented Feb 2, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR implements amortized variational inference via a new AmortizedVIPosterior class, 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 VIPosterior trains an unconditional variational distribution q(θ) for a fixed observation x_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 new x without 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 flow q(θ|x) by optimizing the ELBO against a potential function from NLE/NRE:

from sbi.inference import AmortizedVIPosterior, ZukoFlowType

posterior = AmortizedVIPosterior(
    potential_fn=potential_fn,
    prior=prior,
    flow_type=ZukoFlowType.NSF,
)

posterior.train(theta, x, max_num_iters=1000)

# Works for any observation without retraining
samples = posterior.sample((1000,), x=x_new)
samples_batch = posterior.sample_batched((1000,), x=x_batch)

A ZukoFlowType enum 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:

  • Clear separation of concerns (unconditional vs conditional flows)
  • Different training signatures (train() vs train(theta, x))
  • Avoids conditional logic complexity in VIPosterior

ZukoFlowType enum scoping

The ZukoFlowType enum is defined in sbi.neural_nets.factory and reused here:

  • Covers Zuko flows with efficient log_prob (NSF, MAF, NAF, UNAF, SOSPF, NICE, GF, NCSF, BPF)
  • Keeps a shared, Zuko-specific enum for other builders

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:

  • Accuracy via C2ST against ground truth samples
  • Comparison with standard VIPosterior on the same problem
  • Gradient flow through the ELBO to all flow parameters
  • Correct error handling for edge cases (missing x, untrained model)
  • MAP estimation returns high-density regions
  • Validation batching options to control ELBO evaluation cost

Closes #909

janfb and others added 6 commits January 13, 2026 16:45
…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]>
@janfb janfb self-assigned this Feb 2, 2026
@codecov

codecov Bot commented Feb 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.76596% with 128 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@1bd7fe5). Learn more about missing BASE report.
⚠️ Report is 7 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/inference/posteriors/vi_posterior.py 68.13% 94 Missing ⚠️
sbi/samplers/vi/vi_utils.py 78.40% 19 Missing ⚠️
sbi/samplers/vi/vi_divergence_optimizers.py 77.50% 9 Missing ⚠️
sbi/inference/posteriors/posterior_parameters.py 83.33% 2 Missing ⚠️
.../inference/potentials/posterior_based_potential.py 33.33% 2 Missing ⚠️
sbi/neural_nets/net_builders/flow.py 0.00% 1 Missing ⚠️
sbi/utils/user_input_checks_utils.py 88.88% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1751   +/-   ##
=======================================
  Coverage        ?   88.01%           
=======================================
  Files           ?      138           
  Lines           ?    13245           
  Branches        ?        0           
=======================================
  Hits            ?    11658           
  Misses          ?     1587           
  Partials        ?        0           
Flag Coverage Δ
fast 83.70% <72.76%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/__init__.py 100.00% <100.00%> (ø)
sbi/inference/potentials/base_potential.py 92.85% <100.00%> (ø)
...inference/potentials/likelihood_based_potential.py 82.10% <100.00%> (ø)
sbi/inference/potentials/ratio_based_potential.py 100.00% <100.00%> (ø)
sbi/neural_nets/factory.py 81.92% <100.00%> (ø)
sbi/samplers/vi/__init__.py 100.00% <100.00%> (ø)
sbi/sbi_types.py 100.00% <100.00%> (ø)
sbi/neural_nets/net_builders/flow.py 97.10% <0.00%> (ø)
sbi/utils/user_input_checks_utils.py 91.48% <88.88%> (ø)
sbi/inference/posteriors/posterior_parameters.py 83.33% <83.33%> (ø)
... and 4 more

@manuelgloeckler manuelgloeckler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread sbi/inference/__init__.py Resolved
Comment thread tests/amortized_vi_test.py Resolved
Comment thread tests/amortized_vi_test.py Resolved
Comment thread tests/amortized_vi_test.py Resolved
Comment thread tests/amortized_vi_test.py Resolved
Comment thread tests/amortized_vi_test.py Resolved
janfb and others added 12 commits February 2, 2026 19:56
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]>
@janfb

janfb commented Feb 6, 2026

Copy link
Copy Markdown
Contributor Author

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 zuko has in 1D cases: it resorts to a element-wise transform and performs much worse than pyro. My intention was to completely remove the pyro flows to have a unified framework for VI. To this end, I ended up implementing a Gaussian and diag-Gaussian density estimator in PyTorch (not pyro) for the 1D case. Please let me know if you prefer a different approach.

Summary

Unified API

Instead of a separate AmortizedVIPosterior class, we now have a single VIPosterior with two training modes:

  • train() - Single-x VI: trains unconditional q(θ) for a fixed observation
  • train_amortized(theta, x) - Amortized VI: trains conditional q(θ|x) across observations
  • both use zuko as flow backend
  # 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 x

I agree to your points on the tests:

  • Merged test_amortized_vi_training into test_amortized_vi_accuracy
  • Removed redundant comparison test (test_amortized_vs_single_x_vi and gradient flow test)
  • Added fast test (test_amortized_vi_with_fake_potential) for CI coverage
  • Added NRE support via parametrized fixture - accuracy test now runs for both NLE and NRE

@janfb
janfb force-pushed the add-amortized-vip branch from 617d5a4 to 8b48387 Compare February 6, 2026 15:43
janfb and others added 2 commits February 6, 2026 21:21
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]>
@janfb
janfb requested a review from manuelgloeckler February 6, 2026 17:35
from torch import Tensor
from torch.distributions import Distribution

from sbi.samplers.vi.vi_utils import move_all_tensor_to_device

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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().

Comment thread sbi/samplers/vi/vi_utils.py Resolved
Comment thread sbi/samplers/vi/vi_utils.py Resolved

@manuelgloeckler manuelgloeckler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@manuelgloeckler

manuelgloeckler commented Feb 11, 2026 •

Copy link
Copy Markdown
Contributor

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 LikelihoodBasedPotential overwrites the general to method introduced here (i.e. with move_all_tensors_to_device).

The first two I am not sure about. In the previous version one could pass non-module distribution which where wrapped into a ModuleLike object with parameters() and to() but this might got removed.

Not sure we either remove this functionality or reintroduce that.

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.

@manuelgloeckler manuelgloeckler Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if we should generally recommend gaussian for 1d (are all the flows unstable in 1d?)

@manuelgloeckler manuelgloeckler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, looks great!

I think this kinda now also 'half solves' the #1721 by removing the method keywords from sample. Now that we also have both amortized and nonamortized VI I feel we could add an How to guide or Tutorial on this topic. I created an issue for that (i.e. #1765)

@janfb

janfb commented Feb 16, 2026

Copy link
Copy Markdown
Contributor Author

Okay, looks great!

I think this kinda now also 'half solves' the #1721 by removing the method keywords from sample. Now that we also have both amortized and nonamortized VI I feel we could add an How to guide or Tutorial on this topic. I created an issue for that (i.e. #1765)

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.

@janfb
janfb merged commit 8f91ca3 into main Feb 16, 2026
9 checks passed
@janfb
janfb deleted the add-amortized-vip branch February 16, 2026 08:45
janfb added a commit to SahilKumar75/sbi that referenced this pull request Oct 17, 2026
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.
janfb added a commit that referenced this pull request Oct 17, 2026
* 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]>
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.

Amortized Variational Inference

2 participants