Skip to content

z_score correct order in Zuko - #1492

Merged
janfb merged 1 commit into
sbi-dev:mainfrom
anastasiakrouglova:zuko_z_score_order
Mar 19, 2025
Merged

janfb merged 1 commit into
sbi-dev:mainfrom
anastasiakrouglova:zuko_z_score_order

Conversation

@anastasiakrouglova

Copy link
Copy Markdown
Collaborator

Bug resolved:

The order of the transformations and standardization has been changed: we first want to standardize the input and then perform a series of transformations.

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

good catch!

do we have a test showing how it fails and how this change fixes it?

relevant for @turnmanh ?

@codecov

codecov Bot commented Mar 19, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 79.04%. Comparing base (c5c511c) to head (75018ae).
Report is 4 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##             main    #1492       +/-   ##
===========================================
- Coverage   89.69%   79.04%   -10.66%     
===========================================
  Files         121      121               
  Lines        9347     9347               
===========================================
- Hits         8384     7388      -996     
- Misses        963     1959      +996     
Flag Coverage Δ
unittests 79.04% <ø> (-10.66%) ⬇️

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

Files with missing lines Coverage Δ
sbi/neural_nets/net_builders/flow.py 93.12% <ø> (ø)

... and 37 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gmoss13

gmoss13 commented Mar 19, 2025

Copy link
Copy Markdown
Contributor

Double checked this and I think you're right @anastasiakrouglova, agreed that it's great that you caught this! As a test, I suggest doing a quick test (i.e. without training), because even if the input data is not normalized the network might be able to learn something good (indeed this may have been happening already).

I have a quick idea and will post the results here asap

@gmoss13

gmoss13 commented Mar 19, 2025

Copy link
Copy Markdown
Contributor

Ok, here is the sanity check I promised:

#import stuff
from sbi.utils.sbiutils import standardizing_transform_zuko
from zuko.lazy import LazyComposedTransform
from zuko.flows import UnconditionalTransform
from zuko.transforms import SigmoidTransform
import torch

#define data with very large scale

torch.random.manual_seed(0)
theta = 10000*torch.randn(1000,5)


#define a standardizing transform and a sigmoid transform (which maps everything to (0,1))
transform1 = standardizing_transform_zuko(theta)
transform2 = UnconditionalTransform(SigmoidTransform)
#compose the transforms in both orders
standardizing_first = LazyComposedTransform(*[transform1,transform2])
standardizing_last = LazyComposedTransform(*[transform2,transform1])

#Because the data has a large range, the standardizing transform essentially divides the data by 10000. 
#If the standardizing transform is called after the sigmoid, then everything will get mapped to 0.
#If the standardizing transform is called before the sigmoid, then we apply sigmoid roughly to
#standardized data, giving a reasonable scale for our outputs without training.

z1 = standardizing_first()(theta)
z2 = standardizing_last()(theta)

print(f"data range standardizing first: min:{z1.min().item():.4f}, max:{z1.max().item():.4f}")
print(f"data range standardizing last: min:{z2.min().item():.4f}, max:{z2.max().item():.4f}")

This gives the output:

data range standardizing first: min:0.0160, max:0.9850
data range standardizing last: min:-0.0337, max:0.0561

So indeed we should be calling the standardizing transform first, not last as before the change from @anastasiakrouglova.
From my perspective, this PR can be merged, with this discussion for reference. It does not make sense to add an additional test of this for the test suite, but will wait to see what @janfb thinks.

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

Yes, makes sense and we can merge this now!

Thanks @gmoss13 for the double-check and thanks again @anastasiakrouglova for this important bug fix! 🎉

@janfb
janfb merged commit a1d7555 into sbi-dev:main Mar 19, 2025
@janfb janfb mentioned this pull request Jul 24, 2025
janfb pushed a commit that referenced this pull request Oct 29, 2026
…2105)

build_zuko_unconditional_flow applied the z-score after the flow transforms, so the transforms saw raw data. For data far from 0 or at a small scale, NSF splines sat in their identity tails and the flow stayed at the Gaussian of the z-score with zero gradients, and MAF trained on badly scaled inputs. Both Zuko builders now add the z-score first through one helper, as the conditional flows have done since PR #1492. This affects MarginalTrainer, marginal_nn, and VIPosterior with a user-supplied theta_transform; VI's default link transform already standardized theta.

NCSF models data on [-pi, pi), which no affine z-score preserves. Both NCSF configs now offer z_score_input="none" only, both builders raise for an NCSF with an input transform, and build_zuko_ncsf and marginal_nn default to no z-score for NCSF.

marginal_nn now builds the per-model marginal configs, so it passes num_bins on as Zuko's bins and builds the same flow as MarginalNSFConfig for the same settings. A setting the chosen model does not use now raises, as in the other factories, and None is no longer read as unset for its integer arguments. The marginal and conditional configs of NSF, NCSF, BPF and SOSPF now offer randperm, which Zuko accepts for all flows built on MAF. marginal_nn no longer takes num_components, which never reached a marginal flow, and the legacy MarginalFlowConfig and its base _EstimatorBuilderBase are removed.

Flows saved with state_dict before this change do not load into flows built after it, because the transform order changed: a strict load raises, and a non-strict load puts weights into the wrong layers. Pickled estimators keep their old order and behaviour.

Closes #2114.
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.

3 participants