Numerical stability across running-moment metrics — unified plan (tracking #3662 / #3672 / #3741)
Following @vfdev-5's suggestion in #3662, opening this as the umbrella issue so we can plan the numerical-stability work across all metrics that compute variance / covariance from running sums.
Problem
Several Ignite metrics maintain separate running sums (Σx) and running sums-of-squares (Σx²) and combine them at compute() time as Σx² − (Σx)²/n. This is the textbook naive variance formula and suffers from catastrophic cancellation in float32 whenever |E[X]| is large relative to Var[X]. Concrete failure mode in #3662: PearsonCorrelation returned 0.89 instead of 0.99 on data with mean=1e6, std=1.
Affected metrics
| Metric | File | State |
|---|---|---|
PearsonCorrelation |
ignite/metrics/regression/pearson_correlation.py |
Fixed in #3741 via Welford's online algorithm + parallel merge |
R2Score |
ignite/metrics/regression/r2_score.py:80 |
Same naive formula in the denominator (_y_sq_sum - _y_sum**2 / _num_examples). Reproduces the bug for any target distribution with a large mean. |
Audited and confirmed not affected: MeanSquaredError, PSNR (squared residuals, no Σ(x²) − (Σx)²/n step), HSIC (per-batch accumulator), SSIM (uses constants), SpearmanRankCorrelation / KendallRankCorrelation (delegate to SciPy on buffered data), MaximumMeanDiscrepancy (kernel sums).
If anyone spots another metric I missed, please add to the table above.
Proposed unified fix
Extract the Welford state + parallel-merge logic that #3741 introduces into a small shared helper, then have each affected metric consume it:
ignite/metrics/_running_stats.py # new
class WelfordState:
mean, m2, n # univariate
update(batch)
merge(other)
class WelfordCovState(WelfordState):
mean_x, mean_y, m2_x, m2_y, c_xy, n
update(batch_x, batch_y)
merge(other)
Each metric keeps its own WelfordState (or WelfordCovState for covariance / correlation), updates it in update(), and reads variance / covariance properties in compute(). sync_all_reduce extends to merge state across ranks via merge() rather than summing individual buffers.
Migration order
- PearsonCorrelation — already in flight in #3741. Land that PR, then refactor inward to call the shared helper. (No behavior change; just dedup.)
- R2Score — replace the naive
_y_sq_sum / _y_sumpair with aWelfordStateovery. Add a regression test mirroring #3662's failure case (mean=1e6, std=1). - Future metrics — anyone landing a new variance-bearing metric uses the shared helper from the start.
Existing PRs referenced by this umbrella
- #3672 — earlier attempt at the PearsonCorrelation fix
- #3741 — current Welford-based implementation (mine)
Happy to drive the refactor end-to-end if maintainers are aligned: land #3741 as the prototype, then open follow-up PRs for the helper extraction and the R2Score port.
@joemunene-by thanks for making the tracking issue and suggestions on how to improve the existing metrics! I'm ok with what you propose to do, however let's make the WelfordState attribute names more clear. I would prefer to keep it the simple possible, for example, should we really have two classes: WelfordState and WelfordCovState ? If we need to improve variance computation, we can just have WelfordVariance class (https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford%27s_online_algorithm) and do everything with it. Would this be possible?
Thanks @vfdev-5. Agreed on the names: m2 and c_xy are jargon, fine internally but bad as public attributes.
Revised proposal, with renames and a couple of clarifying docstrings inline:
class WelfordState:
"""Running mean and sum-of-squared-deviations for a single variable.
Updated via the Welford algorithm. Mergeable across ranks via the
Chan/Welford parallel formula.
"""
n_samples: int # count of samples seen so far
mean: float # running mean
sum_sq_dev_from_mean: float # Σ (x_i - mean)^2
@property
def variance(self) -> float:
return self.sum_sq_dev_from_mean / self.n_samples
def update(self, batch): ...
def merge(self, other): ...
class WelfordCovState:
"""Running means, sums-of-squared-deviations, and sum-of-product-of-deviations
for a pair of variables (x, y). Source of variance, covariance, and
Pearson correlation in a numerically stable way.
"""
n_samples: int
mean_x: float
mean_y: float
sum_sq_dev_x: float # Σ (x_i - mean_x)^2
sum_sq_dev_y: float # Σ (y_i - mean_y)^2
sum_product_of_devs: float # Σ (x_i - mean_x)(y_i - mean_y)
@property
def variance_x(self) -> float: ...
@property
def variance_y(self) -> float: ...
@property
def covariance(self) -> float: ...
@property
def pearson_r(self) -> float: ...
Mapping from the existing names in #3741, so reviewers can diff easily:
| #3741 internal name | Public name in the helper |
|---|---|
_mean_x, _mean_y |
mean_x, mean_y |
_m2_x, _m2_y |
sum_sq_dev_x, sum_sq_dev_y |
_c_xy |
sum_product_of_devs |
_num_examples |
n_samples |
If those names work for you, I will:
- Land #3741 as-is. It already has the test coverage and the failure-mode regression test for
mean=1e6, std=1. - Open a follow-up PR that extracts
WelfordStateandWelfordCovStateintoignite/metrics/_running_stats.pywith the names above, and refactorsPearsonCorrelationto consume them. Pure refactor, no behavior change. - Open a third PR that ports
R2ScoretoWelfordState, with a parallel regression test wherey_trueis drawn aroundmean=1e6, the naive formula returns0.0or garbage, and the Welford-based formula returns the true R² within tolerance.
Anything you would like different on the names before I start the helper extraction?
@joemunene-by
If we need to improve variance computation, we can just have WelfordVariance class (https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford%27s_online_algorithm) and do everything with it. Would this be possible?
How about this?
I propose to do in a different order:
- PR to make ignite/metrics/_running_stats.py with necessary WelfordVariance and maybe WelfordCovariance
- PR to update R2Score using WelfordVariance
- update existing PR for PearsonCorrelation to use WelfordCovariance
Perfect, agreed on both fronts. Renaming the classes by purpose (variance / covariance) rather than implementation (state) is clearer for anyone reading ignite/metrics/_running_stats.py cold, and landing the helper first means the two consumer PRs each diff against a stable shared API.
Final API I'll ship in PR 1:
class WelfordVariance:
"""Numerically stable running variance via Welford's online algorithm.
Updated incrementally as batches arrive. Mergeable across ranks via
the Chan / Welford parallel formula.
"""
n_samples: int # count of samples seen so far
mean: float # running mean
sum_sq_dev_from_mean: float # Σ (x_i - mean)^2
def update(self, batch: torch.Tensor) -> None: ...
def merge(self, other: "WelfordVariance") -> None: ...
@property
def variance(self) -> float:
return self.sum_sq_dev_from_mean / self.n_samples
@property
def std(self) -> float:
return self.variance ** 0.5
class WelfordCovariance:
"""Numerically stable running covariance for a pair of variables (x, y).
Provides variance_x, variance_y, covariance, and Pearson correlation
via the same online + parallel-merge approach.
"""
n_samples: int
mean_x: float
mean_y: float
sum_sq_dev_x: float # Σ (x_i - mean_x)^2
sum_sq_dev_y: float # Σ (y_i - mean_y)^2
sum_product_of_devs: float # Σ (x_i - mean_x)(y_i - mean_y)
def update(self, batch_x: torch.Tensor, batch_y: torch.Tensor) -> None: ...
def merge(self, other: "WelfordCovariance") -> None: ...
@property
def variance_x(self) -> float: ...
@property
def variance_y(self) -> float: ...
@property
def covariance(self) -> float: ...
@property
def correlation(self) -> float: ... # Pearson r
Plan, in your order:
- PR 1: add
ignite/metrics/_running_stats.pywithWelfordVarianceandWelfordCovariance. Self-contained: tests cover update + merge + numerical-stability regression (the samemean=1e6, std=1failure case from #3662). No metric changes. - PR 2: port
R2ScoretoWelfordVarianceovery. Adds a regression test mirroring the failure mode. - PR 3: update #3741 to drop the inline Welford state and consume
WelfordCovarianceinstead. Pure refactor on top of the existing review.
I will open PR 1 against master shortly. Will ping you here once it is up.
PR 1 is up: #3750 (feat(metrics): add WelfordVariance and WelfordCovariance helpers).
Self-contained: just ignite/metrics/_running_stats.py plus 20 unit tests in tests/ignite/metrics/test_running_stats.py. No existing metric is touched in this PR. Local run is 20 / 20 green, ruff format --check and ruff check are clean. Whenever you have a chance to review.
PR 2 (R2Score port) and PR 3 (PearsonCorrelation refactor on top of #3741) will follow once this lands.