Re-enable time-dependent z-scoring for Flow Matching#1752
Re-enable time-dependent z-scoring for Flow Matching#1752satwiksps wants to merge 16 commits intosbi-dev:mainfrom
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #1752 +/- ##
==========================================
- Coverage 88.54% 88.20% -0.35%
==========================================
Files 137 138 +1
Lines 11515 13467 +1952
==========================================
+ Hits 10196 11878 +1682
- Misses 1319 1589 +270
Flags with carried forward coverage won't be shown. Click here to find out more.
|
|
It seems Since this failure is in The actual Flow Matching benchmarks and integration tests for this PR passed successfully though |
this was an old bug that surfaced now likely because codecov was trying to serialize things.
Yes, this is unrelated and popped up here by chance or because of an unrelated change in a downstream package. I pushed a fix to this branch ✅ |
|
Thanks for working on this @satwiksps ! Overall, this looks exactly right. However, after reviewing the code and tracing through the flow matching implementation, I believe the z-scoring formula is inverted relative to the interpolation convention (quite confusing!) The interpolation in the loss function is:
So the expected input mean at each time is:
Current PR formula:
This gives mu_t = 0 at t=0 and mu_t = mean_data at t=1 — exactly backwards. Correct formula should be:
The formula only matches at t=0.5 and is maximally wrong at the boundaries. Note on To verify this, I suggest the following test: The standard linear Gaussian test, but with uniform prior between 95 and 100, and with data Can you confirm this (maybe I got confused with the integration directions after all)? |
manuelgloeckler
left a comment
There was a problem hiding this comment.
Hey @satwiksps !
Thanks for the contribution! I checked with main and as of now it does I guess on average perform very similar if not a bit worse than before (although, I think thats mostly fine i.e. these tasks).
I wonder if it would make sense to improve the "preconditioning" a bit more (see comments).
Thanks for adding the comparison to |
|
Alright, I looked at it again and I realized that my proposal was actually incorrect. The formulas I proposed would result in total normalization, i.e., "independent" z-scoring, where all time steps have equal zero mean after z-scoring and we lose valuable time-depenedent information - sorry @satwiksps , your formulas where actually correct! What Manuel proposed is great, we z-score with respect to the Gaussian baseline, e.g., what one would expect when the posterior is actually Gaussian. Then the flow matching network only has to learn the residual from this ideal baseline (please correct me @manuelgloeckler if this intuition is inaccurate). I tested this locally with the following setup:
Results:
Thus, @satwiksps I suggest you implement both options, your proposal and Manuel's proposal and add the test as a new z-scoring test and confirm the results. |
|
@janfb The preconditioning is with respect to the "prior" not the posterior (as this would require regression from x). I don't think that it will "hurt" in almost all cases i.e. FM nets are initialized to output zero hence effectively will let the initialized network sample from a mass covering Gaussian approximation of the prior (and everything else needs to be learned). Nonetheless having an option to disable it is always good. Agree that the benchmark tests are not really sensitive to the z-scoreing, but as we usually enable z-scoreing by default it shouldn't hurt performance even if its not necessary. But as said the deviation is small enough to be fine (and might improve with the additional baseline). |
janfb
left a comment
There was a problem hiding this comment.
Thanks for the update @satwiksps ! looks good, I just have one crucial question on the standard z-scoring formulas again, please check 🙏
|
|
||
| inference_gauss = FMPE( | ||
| prior, | ||
| z_score_x="independent", |
There was a problem hiding this comment.
just to be sure, the z-scoring affects the data only as it's therefore fine to have it as "independent" (because data is not structured here).
but internally, the flow-time z-scoring will happen according to the gaussian_baseline option, yes?
There was a problem hiding this comment.
Yes the z_score_x="independent" only handles the initial, static normalization of the training data. internally, the FlowMatchingEstimator then performs the dynamic, time-dependent z-scoring based on the gaussian_baseline flag
| mu_t = (1 - t_view) * mean_1_view | ||
| var_t = ((1 - t_view) * std_1_view) ** 2 + t_view**2 + 1e-5 |
There was a problem hiding this comment.
wait, this is the formula I suggested, no? and we discussed that this is actually not what we would want here because it normalizes to zero and performs worse (see table).
Please double check this change. We should use your initially suggested formula as one option, and the gaussian_baseline formulas as the second (default) option.
There was a problem hiding this comment.
Oh, sorry @janfb I should have read the conversation properly, using the (1-t) formula without the baseline does indeed force inputs to zero.
| if self.gaussian_baseline: | ||
| mu_t = (1 - t_view) * mean_1_view | ||
| var_t = ((1 - t_view) * std_1_view) ** 2 + t_view**2 + 1e-5 | ||
|
|
||
| std_t = torch.sqrt(var_t) | ||
| input_norm = (input - mu_t) / std_t | ||
|
|
||
| num = t_view - (1 - t_view) * std_1_view**2 |
There was a problem hiding this comment.
I think this is still wrong (but my previous comment also was a bit incomplete, sorry).
Your previous approach was already right, the gaussian_baseline should just additively extend i.e. I would suggest the following (but I might miss something).
mu_t = t_view * mean_1_view
var_t = (t_view * std_1_view) ** 2 + (1 - t_view) ** 2 + 1e-5
std_t = torch.sqrt(var_t)
input_centered = x - mut
input_norm = input_centered / std_t
v_out = self.net(input_norm, condition_emb, time)
v = v_out * std_t
if self.gaussian_baseline:
k_t = (t_view * std_1_view**2) / var_t
x1_hat = mean_1_view + k_t * x_centered
v_affine = (t_view * input) + (1-t_view) * x1_hat
v += v_affine| self.noise_scale = noise_scale | ||
| self.gaussian_baseline = gaussian_baseline | ||
|
|
||
| mean_1_tensor = torch.as_tensor(mean_1).expand(input_shape) |
There was a problem hiding this comment.
I think we do not have to always extend mean_1 and std_1 by default i.e. if its a scalar then we should keep it as a scalar, if its a vector we check that its of size input_shape (or can be reshape into input_shape) otherwise we raise an error. This would save a bit of memory.
However, note that this would require adjusting the forward implementation.
|
|
||
|
|
||
| @pytest.mark.slow | ||
| def test_fmpe_shifted_data_gaussian_baseline(): |
There was a problem hiding this comment.
I would adapt this test: At initialization FM nets will produce zero on any input. So this basically tests if predicting 0 is better to predicting "something".
Instead, I think a better tests would be to:
- Switch to a shifted Gaussian prior (with similar extreme values)
- init FMPE with gaussian baseline, append simulations, and build a posterior + sample (untrained!)
- compare samples to prior (i.e.sample mean/var vs prior mean var, or c2st to prior samples).
The preconditioning with Gaussian baseline should transport the samples to the prior (which should be tested here).
manuelgloeckler
left a comment
There was a problem hiding this comment.
Thanks for you contribution.
I think the formula is still a bit off (but it also was never very clearly defined by us anyway (: ).
I do have a minor suggestion on t he mean,var buffers as well as the gaussian baseline test, which should be addressed (see comments). Once this done, we can merge it :)
Kind regards,
Manuel

Description
This PR re-introduces z-scoring for Flow Matching estimators using a time-dependent normalization approach and adds a Gaussian Baseline for improved training stability.
As discussed in #1623, standard z-scoring is problematic because the network input evolves from data to noise. This implementation provides two distinct normalization modes to handle this evolution while maintaining training stability.
Corrected Normalization Statistics:$t=0$ as Data and $t=1$ as Noise, the statistics are handled based on the chosen mode:
Since we define
Gaussian Baseline ($N(0, 1)$ across the entire path. The drift signal is handled by the hard-coded affine baseline.
gaussian_baseline=True): Normalizes inputs toVariance Only ($t=0$ . This ensures the network can still learn the drift signal when no baseline is used.
gaussian_baseline=False): Normalizes variance while preserving the raw data location atGaussian Baseline:
We implemented an affine vector field baseline (enabled by default). The network now learns the residual vector field with respect to the optimal Gaussian probability path, significantly improving convergence on shifted datasets.
Related Issues/PRs
Changes
sbi/neural_nets/net_builders/vector_field_nets.py: Updatedbuild_vector_field_estimatorto calculate training data statistics, accept thegaussian_baselineflag, and pass them to the estimator.sbi/neural_nets/estimators/flowmatching_estimator.py:mean_1andstd_1as buffers and expanded them to matchinput_shapeto ensure compatibility with multi-dimensional data in CI.forward()to support both Gaussian Baseline (residual learning) and Variance-only (signal preserving) modes.1e-5) to variance calculations to prevent division-by-zero errors.tests/linearGaussian_vector_field_test.py:test_fmpe_time_dependent_z_scoring_integration: Verifies statistics population, buffer registration, and forward pass shapes.test_fmpe_shifted_data_gaussian_baseline: Verifies that the Gaussian Baseline outperforms variance-only scaling on shifted data (Verification
Verification
gaussian_baseline=Trueachieves lower validation loss and faster convergence than variance-only scaling on a shifted 1D prior (z_score_x='independent'.sbibenchmarks locally (pytest --bm --bm-mode fmpe) to check for stability and performance. All 12 tests passed successfully.