ignite icon indicating copy to clipboard operation
ignite copied to clipboard

fix(metrics): use Welford's algorithm in PearsonCorrelation for numerical stability

Open joemunene-by opened this issue 7 months ago • 3 comments

Summary

Fixes #3662

  • Replace the naive sum-of-squares variance formula (E[x²] - E[x]²) with Welford's online algorithm for numerically stable computation
  • Internal accumulators use float64 to further guard against precision loss
  • Distributed sync uses parallel Welford merge via idist.all_gather instead of sum-based @sync_all_reduce

The problem

The naive formula suffers from catastrophic cancellation in float32 when input values have large magnitudes relative to their variance. For example, with mean=1e6 and std=1:

Method Result Error vs scipy
Old (naive float32) 0.8944 10.0%
New (Welford float64) 0.9947 0.003%

Changes

  • pearson_correlation.py: Replaced sum-based state (_sum_of_y_pred_squares, etc.) with Welford state (_mean_x, _mean_y, _m2_x, _m2_y, _cxy). Batch updates use the parallel variant of Welford's algorithm. Distributed merge gathers per-process states and merges them pairwise.
  • test_pearson_correlation.py: Updated accumulator attribute names in tests. Added test_numerical_stability that validates correctness with large-mean, small-variance data fed in small batches.

Test plan

  • [x] All existing tests pass (test_zero_sample, test_wrong_input_shapes, test_degenerated_sample, test_pearson_correlation, test_integration_pearson_correlation, test_accumulator_detached)
  • [x] New test_numerical_stability passes — verifies the fix against the exact scenario described in #3662
  • [ ] Distributed tests (TestDistributed) — updated attribute names, needs CI with distributed backends to verify

joemunene-by avatar Apr 16 '26 00:04 joemunene-by

I think variables names should be changed, as while I am reviewing I have no idea which variables is for what as there name is so confusing.

aaishwarymishra avatar Apr 18 '26 14:04 aaishwarymishra

I think we should wait for now as there is one more pr for issue :)

aaishwarymishra avatar Apr 18 '26 14:04 aaishwarymishra

Thanks for the review! You're right that the accumulator names are opaque without context — I kept _m2_x / _cxy because they mirror the Welford / Chan et al. literature, but added a block comment mapping each attribute to its role, plus inline notes on the batch-merge and distributed-merge formulas (why a plain sum across ranks is wrong, what the n_a·n_b/n_ab · Δ² correction term represents). Pushed in df1fde02.

Happy to wait for maintainer direction on which of this PR and #3740 to land — the two approaches are complementary (float64 alone vs. algorithmic stability via Welford). Noted in #3662 that the shared-utility refactor across PearsonCorrelation, R2Score, and FID is being treated as follow-up work, so this PR stays scoped to fixing the one metric.

joemunene-by avatar Apr 19 '26 01:04 joemunene-by