Skip to content

fix: structured z-scoring takes the per-sample std over the whole event - #2171

Merged
janfb merged 1 commit into
sbi-dev:mainfrom
G26karthik:fix-structured-zscore-event-dims
Nov 24, 2026
Merged

janfb merged 1 commit into
sbi-dev:mainfrom
G26karthik:fix-structured-zscore-event-dims

Conversation

@G26karthik

@G26karthik G26karthik commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

With z_score_x="structured", the per-sample std is taken over dim 1 only, while the mean already pools every event dimension. The docstrings of z_standardization and standardizing_net say the std is computed per sample first and then averaged, which matches what happens for (N, D) data, but not for data with more than one event dimension:

  • For x of shape (N, 1, H, W), the input form CNNEmbedding documents, the std is taken over a size-1 dimension, so it is NaN for every sample. standardizing_net then fails with "Training data mean or std for standardizing net must not contain NaNs", although the data has no NaNs, and z_standardization returns a NaN std.
  • For (N, C, H, W) or (N, C, T), it becomes the std across channels at each position, a different scale from the per-sample std.

Both functions now flatten each sample before taking the std: torch.std(batch_t[is_valid_t].flatten(start_dim=1), dim=1). For (N, D) data the flatten does nothing, so time series and other 2-D inputs give exactly the same result as before.

Does this close any issues?

No issue, it's a small and clear bug fix.

Anything else we should know?

The new test test_structured_z_scoring_uses_all_event_dims checks event shapes (1, 6, 6), (3, 6, 6) and (2, 18) against batch.flatten(1).std(dim=1).mean() for both functions. They fail on main (a NaN std, the channel-wise value, and the NaN assertion from standardizing_net for (1, 6, 6)) and pass with the change.

#2155 also edits standardizing_net, but a different branch of it, so the two should not conflict.

I reviewed and tested every change myself; AI tools helped with drafting.

Checklist

  • I have read the contributing guide.
  • pytest tests/sbiutils_test.py -k "structured or z_scor" passes, and ruff check and ruff format --check pass on the changed files. I didn't run the full fast suite for this one.
  • I added or updated tests for the changed behavior.
  • I used Google-style docstrings for new or changed public functions. (No public function changed.)
  • (If applicable) I reported how long new tests run and marked slow ones with pytest.mark.slow. The new test only builds small tensors and trains nothing.

The per-sample std was taken over dim 1 only, while the mean pools every event dimension. For (N, 1, H, W) input it was NaN; for (N, C, ...) it was the std across channels. Flatten each sample first; (N, D) input is unchanged.
@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Structured z-scoring now computes standard deviations across each sample’s flattened event dimensions in both standardization functions. Tests cover three event shapes and check the calculated values.

Changes: Structured z-scoring

Layer / File(s) Summary
Flattened event standard deviation
sbi/utils/sbiutils.py, tests/sbiutils_test.py
z_standardization and standardizing_net now compute each sample’s standard deviation after flattening its event dimensions. Tests check both functions across three event shapes.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: janfb, manuelgloeckler

Merge Risk: Minimal · up to dabc1

Structured z-scoring now uses a single per-sample standard deviation over the whole event, which removes NaNs and channel-wise scaling for multi-dimensional events. No actionable merge risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: structured z-scoring now takes the per-sample std over the whole event. The raw summary confirms that z_standardization and standardizing_net flatten each sample's non…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description covers the change, the bug it fixes, and the new test. It cites the affected input shapes and the failure modes, and it says (N, D) inputs are unchanged. The checklist is filled in w…
Full details: Title check

Explanation

The title names the main change: structured z-scoring now takes the per-sample std over the whole event. The raw summary confirms that z_standardization and standardizing_net flatten each sample's non-batch dimensions before computing the std, and the tests cover that behavior.

Full details: Description check

Explanation

The description covers the change, the bug it fixes, and the new test. It cites the affected input shapes and the failure modes, and it says (N, D) inputs are unchanged. The checklist is filled in with the commands run and their results. The issue section says no issue is linked, which is acceptable here. The AI-assistance disclosure is present, which the template asks for. The only unchecked box is the docstring item, and the author explains that no public function changed. The description is complete and specific, so it passes.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c980e840-9e1c-4f96-884d-6baf1bb884eb
Commits

Reviewing files that changed from the base of the PR and between 9d082fe and dabc13d.

Files selected for processing: 2

  • sbi/utils/sbiutils.py
  • tests/sbiutils_test.py

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.55%. Comparing base (9d082fe) to head (dabc13d).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2171      +/-   ##
==========================================
+ Coverage   88.77%   89.55%   +0.78%     
==========================================
  Files         142      142              
  Lines       14898    14898              
==========================================
+ Hits        13225    13342     +117     
+ Misses       1673     1556     -117     
Flag Coverage Δ
fast 87.48% <100.00%> (?)

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

Files with missing lines Coverage Δ
sbi/utils/sbiutils.py 90.19% <100.00%> (+0.73%) ⬆️

... and 64 files with indirect coverage changes

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

@G26karthik thanks, the fix looks good! I also ran NPE with a CNN embedding on single-channel images of shape (1, 16, 16): it stopped with the NaN assertion before and trains now.

One correction to the description: PR #2155 does touch the same lines, since it lets standardizing_net reuse z_standardization. I will resolve that in PR #2155 after this one is merged, so nothing is needed from you.

Thanks for fixing this, Jan

@janfb
janfb merged commit b3f5f5d into sbi-dev:main Nov 24, 2026
18 checks passed
@G26karthik

Copy link
Copy Markdown
Contributor Author

Thanks, Jan, also for trying it with a CNN embedding. Noted on #2155, and thank you for handling it there.

janfb added a commit that referenced this pull request Nov 26, 2026
…-tensors

The conflict in sbiutils.py keeps PR #2171's per-sample std over the flattened event inside the shared z_standardization, which standardizing_net now calls.
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.

2 participants