Repository navigation
Simformer - #1621
Simformer#1621
Conversation
manuelgloeckler
left a comment
There was a problem hiding this comment.
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.
…ng time, edge mask of None can be used, minor fixes
…ce in Simformer and MaskedVectorFieldTrainer
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
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 :) |
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
manuelgloeckler
left a comment
There was a problem hiding this comment.
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-devicefor 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.
# 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
Benchmark (updated)Mini-sbibm on the current branch (
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. |
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
The Simformer diverges from the standard sbi paradigm of data provided by means of
thetaandx, it rather exploits a full tensorinputsof data and two masks:condition_maskto identify which variables are latent (to be inferred by the Simformer) and which are observed (ground data)edge_maskto 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.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.
MaskedConditionalVectorFieldEstimatoris exactly below the code block ofConditionalVectorFieldEstimator; and they simply consist in an overall re-factor of the original counterpart, where each use of a "thetaandx" or "inputsandcondition" has been replaced with a general "inputs,condtion_mask, andedge_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$(\theta, x)$ setting to the full input tensor, and back.
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()anddisassemble_full_inputs(), which are able to convert between theAt inference time, an
edge_maskcan be specified, otherwise it will beNone(equivalent to a full ones tensor, but memory safer),condition_maskinstead must be specifically passed atbuild_conditionaltime; another option is to directly use thebuild_posterior()andbuild_likelihood()method which will automatically generate an appropriate condition_mask based onposterior_latent_idxandposterior_observed_idxparameters specified at init() of the Simformer.Also at training time an$\text{Bernoulli}(p=0.5)$ .
edge_maskcan be specified, if not the default value will still beNone, 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 atappend_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 aNote 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 andinf's) natively, ifhandle_invalid_x=Truethen 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-sbibmbenchmakr suite, and a notebook tutorial for the Simformer (underadvanced_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:
mean_t,std_tetc. into some standard Mixins (e.g., instead ofVEScoreEstimator(ConditionalScoreEstimator)one now haveVarianceExplodingSDEwhich definedmean_t,std_tetc., andVEScoreEstimatorbecomesVEScoreEstimator(ConditionalScoreEstimator, VarianceExplodingSDE); so that I can also define easilyMaskedVEScoreEstimator(MaskedConditionalScoreEstimator, VarianceExplodingSDE)without repeating the VE SDE pieces.)NeuralInferenceinterface, which has been split using a Mixin too (BaseNeuralInference) which defines shared properties of bothNeuralInferenceandMaskedNeuralInference, this also requested some minor adjustments mainly for methods such as_resolve_prior()and_resolve_estimator(), most importantly a newNoPriorobject has been created as a temporary solution for Keep prior optional and remove unnecessary copies of theas from ImproperPrior. #1635ConditionalVectorFieldEstimatorand theMaskedConditionalVectorFieldEstimatorwhere simplified by moving shared code into a Mixin calledBaseConditionalVectorFieldEstimator, mainly regardingmean_base,std_baseproperties, or methods such asdiffusion_fn()Summary of modified files
Files I modified should count to be the following:
sbi/inference
sbi/inference/trainers/base.py: AddedMaskedNeuralInference.sbi/inference/trainers/vfpe/base_vf_inference.py: AddedMaskedVectorFieldEstimatorBuilderandMaskedVectorFieldInference(subclass ofMaskedNeuralInference).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: AddedMaskedConditionalEstimatorandMaskedConditionalVectorFieldEstimator(subclass ofMaskedConditionalEstimator).sbi/neural_nets/estimators/score_estimator.py:MaskedConditionalScoreEstimator(subclass ofMaskedConditionalVectorFieldEstimator), placed directly aboveConditionalScoreEstimator.MaskedVEScoreEstimator(subclass ofMaskedConditionalScoreEstimator).sbi/neural_nets/net_builders/vector_field_nets.py:build_vector_field_estimatorupdated to supportsimformerandmasked-score.MaskedSimformerBlock,MaskedDiTBlock,SimformerNet(subclass ofMaskedVectorFieldNet), andbuild_simformer_network(defines default architecture parameters).sbi/utils
sbi/utils/vector_field_utils.py: AddedMaskedVectorFieldNet.sbi/analysis
sbi/analysis/plots.py: Minor fix to ensure CPU conversion inensure_numpy()(added.cpu()before.numpy()).Unit Test
Introduced benchmarks (
mini_sbibm) and test for the simformer and related masked objects intests/linearGaussian_vector_field_test.pytests/posterior_nn_test.pytests/vector_field_nets_test.pytests/vf_estimator_test.py(which also includes shape tests on the Wrapper)tests/bm_test.pyRegarding 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.ipynbsbi/inference/trainers/vfpe/simformer.py: including both Score-based and Flow-matching Simformer interfacesThank 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!