Skip to content

Simformer - #1621

Merged
manuelgloeckler merged 362 commits into
sbi-dev:mainfrom
nMaax:simformer
Nov 25, 2026
Merged

manuelgloeckler merged 362 commits into
sbi-dev:mainfrom
nMaax:simformer

Conversation

@nMaax

@nMaax nMaax commented Jul 16, 2025 •

Copy link
Copy Markdown
Contributor

Simformer

Important

This PR is part of Google Summer of Code 2025

Note

Before opening this PR, I initially experimented with the Simformer and auxiliary components in a separate branch of my sbi fork. You can find it here. I used such branch (simformer-dev) as a first environment where I could experiment solutions with more freedom, then I opened this PR once I got a minimum viable product. Such branch basically served as my working enviroment for the first month and a half of the GSOC. Nevertheless, all the code I finalized there has been fully incorporated into this PR you are reading.

More specifically, in such branch I mainly worked on a first version of the Simformer neural network architecture and the "masked" interface, I also attempted to introduce a Joint distribution interface, i.e., a parallel interface to the current "Posterior" approach in sbi that could generalize better to the Simformer case—as the Simformer do not work by means of "posterior", "likelihood" or such, but more generally by means of arbitrary conditionals. Neverthless, the later has been dropped to rather implement the use of a Wrapper class that could adapt the more general Simformer approach to the existing sbi posterior interface (see below for more information)

Implemented the Simformer, Gloeckler et al. 2024 ICML. The Simformer aims to unify the various simulation-based inference paradigms (posterior, likelihood, or arbitrary conditional sampling) within a single framework, allowing users to sample from any conditional distribution of interest—potentially acting also by a novel data generator if one samples the unconditioned joint distribution of all variables.

fig1b-1

The Simformer diverges from the standard sbi paradigm of data provided by means of theta and x, it rather exploits a full tensor inputs of data and two masks:

  • A condition_mask to identify which variables are latent (to be inferred by the Simformer) and which are observed (ground data)
  • A edge_mask to identify relationships between variables, equivalent to and adjacency matrix for a DAG. This mask will be directly used by the transformer attention block to mask-out certain attention scores.
white_all_in_one

Design of the Masked Classes

To accomplish this, it has been necessary to create some "parallel" classes of the current ScoreEstimator, VectorFieldEstimator, etc. to work by means of this "masked" paradigm.

Generally, each "Masked" version of other objects are provided exactly below their counterpart in the same python file, e.g. MaskedConditionalVectorFieldEstimator is exactly below the code block of ConditionalVectorFieldEstimator; and they simply consist in an overall re-factor of the original counterpart, where each use of a "theta and x" or "inputs and condition" has been replaced with a general "inputs, condtion_mask, and edge_mask".

It has been also introduced a Wrapper class able to adapt the original API of the Posterior to the Simformer one, thanks to this class one is able to simply call build_conditional() method directly on the Simformer inference object and obtain a standard Posterior object that works as always—given some fixed condition and edge masks. The Wrapper handles all the shapes automatically and perform auxiliary operations to pass the data to a Simformer network and the underlying masked estimator; this is done mainly through two helper functions: assemble_full_inputs() and disassemble_full_inputs(), which are able to convert between the $(\theta, x)$ setting to the full input tensor, and back.

At inference time, an edge_mask can be specified, otherwise it will be None (equivalent to a full ones tensor, but memory safer), condition_mask instead must be specifically passed at build_conditional time; another option is to directly use the build_posterior() and build_likelihood() method which will automatically generate an appropriate condition_mask based on posterior_latent_idx and posterior_observed_idx parameters specified at init() of the Simformer.

Also at training time an edge_mask can be specified, if not the default value will still be None, more generally the user can pass a Callable to generate condition or edge masks, so that one can simply choose the mask distributions they prefer. Sets of tensors/lists or even just one tensor can be passed as well. Masks are also generated just-in-time (JIT) for the training, that is, they are not provided at append_simulation(), but during the train() in order to save up memory. Differently from inference time, here if a condition mask is not specified, a default generator will be used, producing masks sampled by a $\text{Bernoulli}(p=0.5)$.

Note that the Simformer potentially allows the user to set any mask of their choice both at training and inference time, it is rather duty of the user to provide coherent definitions (callables, sets, or fixed tensors) that make sense, e.g. if the user passes a specific edge mask at training time, the Simformer will learn that specific DAG structure, it is then duty of the user to pass a coherent edge_mask also when calling build_conditional, build_posterior or build_likelihood.

Furthermore, the Simformer is also able to manage invalid inputs (nan's and inf's) natively, if handle_invalid_x=True then the Simformer will automatically spot invalid inputs at training time (still JIT) and switch their state on the condition mask as latent (to be inferred), other than also replace such values with small Gaussian noise for numerical stability.

Also, a Flow-matching equivalent of the Simformer (we assumed the above to be score-based) has been provided.

This PR then includes integration with the mini-sbibm benchmakr suite, and a notebook tutorial for the Simformer (under advanced_tutorials/docs), where I showcase its use. I also tried to make the API Reference as clear as possible for documentation.


Refactor of existing code

Parts of the existing code have been refactored, mainly to avoid repetition of code and keep everything DRY. The most important pieces of code that have been modified are:

  1. the SDE Estimators, where we moved the definition of mean_t, std_t etc. into some standard Mixins (e.g., instead of VEScoreEstimator(ConditionalScoreEstimator) one now have VarianceExplodingSDE which defined mean_t, std_t etc., and VEScoreEstimator becomes VEScoreEstimator(ConditionalScoreEstimator, VarianceExplodingSDE); so that I can also define easily MaskedVEScoreEstimator(MaskedConditionalScoreEstimator, VarianceExplodingSDE) without repeating the VE SDE pieces.)
  2. the NeuralInference interface, which has been split using a Mixin too (BaseNeuralInference) which defines shared properties of both NeuralInference and MaskedNeuralInference, this also requested some minor adjustments mainly for methods such as _resolve_prior() and _resolve_estimator(), most importantly a new NoPrior object has been created as a temporary solution for Keep prior optional and remove unnecessary copies of theas from ImproperPrior. #1635
  3. the ConditionalVectorFieldEstimator and the MaskedConditionalVectorFieldEstimator where simplified by moving shared code into a Mixin called BaseConditionalVectorFieldEstimator, mainly regarding mean_base, std_base properties, or methods such as diffusion_fn()

Summary of modified files

Files I modified should count to be the following:

sbi/inference

  • sbi/inference/trainers/base.py: Added MaskedNeuralInference.
  • sbi/inference/trainers/vfpe/base_vf_inference.py: Added MaskedVectorFieldEstimatorBuilder and MaskedVectorFieldInference (subclass of MaskedNeuralInference).
  • sbi/inference/trainers/vfpe/simformer.py: New file introducing the Simformer inference class.

sbi/neural_nets

  • sbi/neural_nets/factory.py: Added support for building Simformer networks (simformer_nn).

  • sbi/neural_nets/estimators/base.py: Added MaskedConditionalEstimator and MaskedConditionalVectorFieldEstimator (subclass of MaskedConditionalEstimator).

  • sbi/neural_nets/estimators/score_estimator.py:

    • Added MaskedConditionalScoreEstimator (subclass of MaskedConditionalVectorFieldEstimator), placed directly above ConditionalScoreEstimator.
    • Added MaskedVEScoreEstimator (subclass of MaskedConditionalScoreEstimator).
  • sbi/neural_nets/net_builders/vector_field_nets.py:

    • build_vector_field_estimator updated to support simformer and masked-score.
    • Introduced MaskedSimformerBlock, MaskedDiTBlock, SimformerNet (subclass of MaskedVectorFieldNet), and build_simformer_network (defines default architecture parameters).

sbi/utils

  • sbi/utils/vector_field_utils.py: Added MaskedVectorFieldNet.

sbi/analysis

  • sbi/analysis/plots.py: Minor fix to ensure CPU conversion in ensure_numpy() (added .cpu() before .numpy()).

Unit Test

Introduced benchmarks (mini_sbibm) and test for the simformer and related masked objects in

  • tests/linearGaussian_vector_field_test.py
  • tests/posterior_nn_test.py
  • tests/vector_field_nets_test.py
  • tests/vf_estimator_test.py (which also includes shape tests on the Wrapper)
  • tests/bm_test.py

Regarding linear gaussian tests, I tried to implement the simformer tests in existing methods as much as possible, nonetheless iid test and sde/ode sampling equivalence are still provided as separate dedicated tests and fixtures

New files

  • docs/advanced_tutorials/22_simformer.ipynb
  • sbi/inference/trainers/vfpe/simformer.py: including both Score-based and Flow-matching Simformer interfaces

Thank you

Thank you sbi and Google for this opportunity. It has been so rewarding implementing the Simformer: not only I learned something completely new itself, but most importantly I understood how to do it: having to familiarize with new concepts, writing code within code made by others, and following indications of mentors are the real value of this experience. Special thanks to my mentors Manuel (@manuelgloeckler ) and Jan (@janfb ) for accepting my proposal, and @manuelgloeckler in particular for having helped me throughout the whole journey!

Comment thread sbi/inference/trainers/base.py Resolved
Comment thread tests/vf_estimator_test.py Resolved
Comment thread tests/vf_estimator_test.py Resolved
Comment thread tests/vf_estimator_test.py Resolved
Comment thread tests/vf_estimator_test.py Resolved
Comment thread tests/vf_estimator_test.py Resolved
Comment thread tests/vf_estimator_test.py Resolved
Comment thread sbi/neural_nets/factory.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.

Overall, great work. I think almost everything is there and nicely implemented.

I think a few things we still can do for the core is:

  • To think of a way to avoid code duplication e.g. in the estimator implementations.
  • It should also be straight forward to support the other sde types, as well as flow matching.

Manuel Gloeckler and others added 8 commits November 10, 2026 19:30
Resolve conflicts with sbi-dev#2104: keep the branch's trainer imports, drop the
now-unused dataclasses.asdict, and use loss_args_to_kwargs in both vector
field trainers (no deep copy of the loss arguments per batch).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Assemble the full input out of place (concatenate latent and observed
  entries, then reorder with a fixed permutation). The in-place index
  writes failed under torch.func.vmap, e.g. for iid sampling with
  iid_method="jac_gauss".
- Broadcast the batch shapes of input and condition like the unmasked
  vector field estimators; fall back to tiling the condition and raise a
  clear error if neither applies (previously a silent empty repeat).
- Register the latent/observed indices as (non-persistent) buffers so
  they follow the wrapper to another device.

Tests: assembly order and broadcasting, vmap, device move of the index
buffers, and iid posterior sampling with all iid methods.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…th variants

- Route builder kwargs by name: arguments of the masked estimator class
  (sigma_min/max, beta_min/max, t_min/max, weight_fn, noise_scale) go to
  the estimator, arguments of build_simformer_network to the network.
  Unknown arguments, and network arguments with a custom network, now
  raise instead of being silently dropped.
- Compute z-scoring statistics from the finite values of each entry, so
  z-scoring works when every simulation has a missing entry; entries
  with fewer than two finite values are left unscaled (with a warning).
- Score Simformer: z-score inputs per entry by default, as NPSE does.
- Flow Simformer: support z_score_inputs (previously rejected). The
  estimator then trains in standardized space and the fixed-mask wrapper
  maps latent entries back via composed standardization, as FMPE does;
  that mode does not support iid observations, batched sampling or MAP
  yet and raises accordingly. Off by default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Document everywhere what the network does: edge_mask[i, j] = True means
  variable i depends on (attends to) variable j, so a DAG edge j -> i sets
  edge_mask[i, j]; self-edges are always added. The docstrings said "an
  edge from the row variable to the column variable", i.e. the transpose.
- build_conditional/build_posterior/build_likelihood take a (T, T) edge
  mask (the fixed-mask wrapper rejects batched masks); say so.
- Fix the Simformer class docstring formatting and drop the claim that
  the prior is "standard Gaussian noise".
- Test the documented direction via input gradients.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
test_c2st_vector_field_on_linearGaussian hard-coded device="cpu", so its
gpu-marked Simformer cases (vp/subvp, 3D uniform) never touched CUDA.
Pick the device from the gpu marker and compare samples on the CPU.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ies statically

- MaskedFlowMatchingEstimator now normalizes internally, as
  FlowMatchingEstimator does: latent entries are z-scored with the
  marginal statistics of the probability path, the network predicts a
  normalized velocity, and the loss is computed in normalized space.
  Inputs and outputs stay in the original space, so iid sampling, batched
  sampling and MAP keep working. This replaces the standardized-space
  (composed) approach of the previous commit.
- Optional gaussian_baseline: add the analytical Gaussian velocity so the
  network only learns the residual (as in FMPE).
- Both Simformer variants z-score per entry by default (as NPSE/FMPE).
- Observed (clean) entries are encoded with the data statistics instead of
  the time-dependent marginal statistics, which left them unscaled at
  large diffusion times (e.g. VP at t -> 1).

Without z-scoring, the flow Simformer misses the posterior mean by ~111
on data with scale ~1000; with it, the error is ~0.2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@manuelgloeckler

manuelgloeckler commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Alright @nMaax I will get the branch up to date. And fix some minor parts + run the benchmarks today.

Afterwards good to go from my side. I will let you have a last look :)

Manuel Gloeckler and others added 3 commits November 11, 2026 11:50
Restores plot.py, lc2st.py (no global RNG reseeding), misspecification.py,
the NPE/NLE/NRE trainers (ABC base, no _neural_net guards),
vector_field_posterior.py, the mini-sbibm device plumbing and conftest.
bm_test.py keeps only the Simformer path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Trainer:
- Keep the prior passed at init; it is the default prior of build_posterior.
- Mask generators are picklable module-level classes; a set of masks is
  sorted so seeded training is reproducible; unsupported types raise.
- Generator outputs may be unbatched ((T,) / (T, T)); shapes are checked.
- build_conditional/posterior/likelihood default to the training edge mask
  generator (ambiguous random edge masks require an explicit edge_mask).
- Index checks work for CUDA indices; infer() supports the Simformer.
- Shared training code (EMA summaries, validation times) lives in a mixin.
- Restore per-sample loss averaging, estimator-only deepcopy and the
  _neural_net typing of the shared base class.

Losses:
- NaN/Inf entries are latent and excluded from the loss, the control
  variate and the rebalancing count (validity mask); ValueError instead of
  assert when no valid entry is left.
- rebalance_loss counts latent entries (nodes x features), not nodes.

Estimators and networks:
- Wrapper mean_t_fn/std_fn return one trailing dimension.
- A fixed (T, T) edge mask is passed unexpanded; the attention mask is built
  once per forward and need_weights=False.
- simformer_*_nn take an explicit z_score_x and reject embedding_net.

Tests: trainer-level tests (tests/simformer_trainer_test.py), edge mask
equivalence, and a GPU accuracy test with a DAG edge mask.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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.

Benchmark

Results on mini-sbibm with the current branch, compared against NPSE and FMPE. All methods use default hyperparameters, 10k simulations and 2 seeds, with 10 observations per seed. The score is C2ST, where lower is better and 0.5 means the posterior is exact.

Method Gaussian linear Linear MVG 2d SLCP Two moons Mean
Simformer VE 0.519 0.507 0.812 0.583 0.605
Simformer VP 0.520 0.503 0.813 0.772 0.652
Simformer flow 0.527 0.515 0.748 0.742 0.633
NPSE VE 0.577 0.502 0.820 0.631 0.633
NPSE VP 0.578 0.504 0.794 0.764 0.660
FMPE 0.565 0.503 0.828 0.754 0.662
  • On average, each Simformer variant does as well as or better than its unmasked counterpart (VE vs. NPSE VE, VP vs. NPSE VP, flow vs. FMPE). It is clearly better on Gaussian linear and, for the VE variant, on two moons. SLCP is roughly even.
  • The Simformer is more expensive. It trains for about 3.5–6× more epochs and takes 10–20× the training time of NPSE/FMPE: 13–28 min vs. 1–1.5 min per run, with 6 jobs sharing one GPU.
  • Before the control-variate fix, the score-based variants did not train properly (C2ST ≈ 0.94 on Gaussian linear). That is fixed in this branch.

The changes that are not specific to the Simformer were moved out of this PR into separate draft PRs. Based on @nMaax's work here.

  • #2166: L-C2ST with an ensemble of skorch classifiers
  • #2167: mini-sbibm task loader fixes
  • #2168: --bm-device for the benchmark

Thanks @nMaax for implementing and extending the toolbox with the new abstractions allowing estimation of arbitrary conditionals. Good to go from my end. If you have something left to add, feel free to do so.

@janfb if you want to have another look ? Otherwise I will merge it.

Manuel Gloeckler and others added 5 commits November 15, 2026 16:48
# Conflicts:
#	sbi/inference/trainers/base.py
#	tests/bm_test.py
…findings

- Add SimformerNetConfig and Simformer{FlowMatching,VEScore,VPScore,SubVPScore}Config,
  matching the NPSE/FMPE `vf_estimator=` config API; factories build these configs.
- Simformer/FlowMatchingSimformer take `vf_estimator` configs; `sde_type` with a
  config raises like NPSE; no more untyped **kwargs.
- Validate posterior indices (1-D, unique, ascending) and fix the missing-index
  error message.
- Reject non-2-D theta/x in `infer` for masked methods.
- FlowMatchingSimformer samples with ODE by default (like FMPE).
- Raise on unknown `time_emb_type`; remove dead code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r step

A fixed edge mask was expanded to (B, T, T) by the mask generator and the
trainer, and the network then compared all B copies on every forward pass
to collapse them back to (T, T). Converting that comparison to a bool forced
a host-device sync per training and validation step.

A shared (T, T) mask now stays unexpanded from the generator through the
trainer, the score loss and the network, which attention broadcasts over
batch and heads. Per-sample (B, T, T) masks keep their batched path, and the
network no longer checks them for identical entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	sbi/inference/trainers/base.py
# Conflicts:
#	sbi/inference/trainers/vfpe/base_vf_inference.py
#	sbi/neural_nets/estimators/score_estimator.py
#	sbi/neural_nets/net_builders/__init__.py
@manuelgloeckler

Copy link
Copy Markdown
Contributor

Benchmark (updated)

Mini-sbibm on the current branch (a523b2da, up to date with main), compared against NPSE and FMPE. All methods use default hyperparameters (NPSE/FMPE with the default MLP), 2 seeds each. C2ST against reference posteriors (0.5 is best), mean ± sd over seeds.

FlowMatchingSimformer now samples with the ODE by default (like FMPE), so its numbers replace the ones in my earlier review, which used the SDE.

Method two_moons linear_mvg_2d gaussian_linear slcp
1k simulations
Simformer (VE) 0.823 ± 0.004 0.524 ± 0.004 0.566 ± 0.006 0.903 ± 0.006
Simformer (VP) 0.925 ± 0.009 0.514 ± 0.020 0.584 ± 0.013 0.901 ± 0.009
FlowMatchingSimformer 0.845 ± 0.036 0.545 ± 0.023 0.585 ± 0.004 0.919 ± 0.005
NPSE (VE) 0.851 ± 0.007 0.526 ± 0.023 0.659 ± 0.005 0.963 ± 0.001
NPSE (VP) 0.865 ± 0.008 0.526 ± 0.005 0.674 ± 0.038 0.958 ± 0.001
FMPE 0.831 ± 0.006 0.522 ± 0.004 0.690 ± 0.013 0.942 ± 0.003
10k simulations
Simformer (VE) 0.603 ± 0.031 0.510 ± 0.003 0.530 ± 0.004 0.780 ± 0.014
Simformer (VP) 0.819 ± 0.058 0.510 ± 0.005 0.522 ± 0.009 0.847 ± 0.037
FlowMatchingSimformer 0.693 ± 0.011 0.512 ± 0.009 0.528 ± 0.003 0.703 ± 0.011
NPSE (VE) 0.615 ± 0.001 0.511 ± 0.001 0.590 ± 0.006 0.812 ± 0.002
NPSE (VP) 0.760 ± 0.016 0.504 ± 0.003 0.586 ± 0.006 0.800 ± 0.003
FMPE 0.758 ± 0.017 0.504 ± 0.003 0.569 ± 0.011 0.827 ± 0.013

The Simformer (VE) and the FlowMatchingSimformer match or beat NPSE and FMPE on most tasks; the FlowMatchingSimformer is clearly best on SLCP at 10k. The VP Simformer is weaker on two moons and varies more across seeds.

manuelgloeckler and others added 5 commits November 24, 2026 18:15
Replace the linear Gaussian example with a 1D sine model whose likelihood
is simple but whose posterior is multimodal. Lead with a plot of the joint
and show posterior and likelihood as slices through it, then go into the
API details.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rials

- Generate the API pages of Simformer, FlowMatchingSimformer,
  simformer_score_nn and simformer_flow_nn; the overview linked to them, but
  no page was built.
- Fix the bullet lists in the masked-estimator docstrings, which rendered
  as errors in Sphinx.
- List the Simformer in the README, in the implemented-methods tutorial and
  in llms.txt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…erun it

- Describe the prior as N(0, pi^2), as in the code, and the posterior as
  multimodal (sine symmetry and periodicity, weighted by the prior).
- Sort the imports and format the code cells (ruff, as in pre-commit).
- Label the simulations plot.
- Save the outputs of one fresh run, with the progress output compacted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@manuelgloeckler
manuelgloeckler merged commit c3247d5 into sbi-dev:main Nov 25, 2026
18 checks passed
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.

4 participants