ignite icon indicating copy to clipboard operation
ignite copied to clipboard

feat(metrics): add WelfordVariance and WelfordCovariance helpers (PR 1 of #3748)

Open joemunene-by opened this issue 6 months ago • 12 comments

Summary

PR 1 of the plan in #3748: introduces ignite/metrics/_running_stats.py with two numerically stable running-statistics primitives that variance- and covariance-bearing metrics can share, instead of each one rolling its own naive Σx² − (Σx)²/n implementation.

  • WelfordVariance: running mean, variance, std for a single variable.
  • WelfordCovariance: running variance_x, variance_y, covariance, and Pearson correlation() for a paired (x, y) stream.

Both classes:

  • keep internal state in float64 regardless of input dtype, so the classic E[X²] − E[X]² cancellation does not bite at large means (the failure mode from #3662);
  • update incrementally via Welford's online algorithm;
  • expose merge() implementing the Chan / Welford parallel formula, suitable for cross-rank distributed reduction or any other case where two accumulators need to be combined without re-iterating the raw data.

No existing metric is touched in this PR. The helper lands first so the two consumer PRs can each diff against a stable shared API.

Follow-ups (already scoped in #3748)

  • PR 2: port R2Score to WelfordVariance, with a regression test mirroring #3662's mean=1e6, std=1 failure case.
  • PR 3: update #3741 to drop its inline Welford state and consume WelfordCovariance instead. Pure refactor on top of the existing review.

API

class WelfordVariance:
    n_samples: int
    mean: torch.Tensor                       # running mean
    sum_sq_dev_from_mean: torch.Tensor       # M2 = Σ (x_i − mean)^2

    def update(self, batch: torch.Tensor) -> None: ...
    def merge(self, other: WelfordVariance) -> None: ...

    @property
    def variance(self) -> torch.Tensor: ...  # M2 / n
    @property
    def std(self) -> torch.Tensor: ...       # sqrt(variance)


class WelfordCovariance:
    n_samples: int
    mean_x: torch.Tensor
    mean_y: torch.Tensor
    sum_sq_dev_x: torch.Tensor
    sum_sq_dev_y: torch.Tensor
    sum_product_of_devs: torch.Tensor        # Σ (x_i − mean_x)(y_i − mean_y)

    def update(self, batch_x, batch_y) -> None: ...
    def merge(self, other: WelfordCovariance) -> None: ...

    @property
    def variance_x(self) -> torch.Tensor: ...
    @property
    def variance_y(self) -> torch.Tensor: ...
    @property
    def covariance(self) -> torch.Tensor: ...
    def correlation(self, eps: float = 1e-8) -> torch.Tensor: ...  # Pearson r

Tests

20 unit tests in tests/ignite/metrics/test_running_stats.py, all passing locally with pytest tests/ignite/metrics/test_running_stats.py:

WelfordVariance

  • empty accumulator returns zero variance / std without crashing
  • single-batch update matches numpy.mean and numpy.var to 1e-12
  • multi-batch update matches single-batch on the same data
  • merge of two accumulators matches update on the concatenated data
  • merge with an empty accumulator on either side is a no-op or absorbs the other side
  • numerical-stability regression: 10,000 samples at mean=1e6, std=1 in float32; Welford in float64 recovers the true variance, and the same data through the naive Σx² − (Σx)²/n formula in float32 is asserted to fail by ≥ 0.1, so the test documents the failure mode it is protecting against
  • single-sample case (variance is 0, not undefined)
  • empty-batch update is a no-op
  • reset clears state
  • integer input dtypes upcast to float64

WelfordCovariance

  • empty accumulator returns zero everywhere
  • single-batch update matches numpy.cov(..., bias=True) and numpy.corrcoef to 1e-10 to 1e-12
  • multi-batch update matches single-batch
  • merge matches concatenated update
  • numerical-stability regression: 10,000 paired samples at mean=1e6, true correlation > 0.99; Welford recovers r within 1e-4 of the float64 ground truth
  • shape mismatch raises ValueError
  • empty-batch update is a no-op
  • constant-y series returns r = 0.0 (not NaN) via the eps clamp
  • reset clears state

Cross-class sanity

  • WelfordCovariance.variance_x matches WelfordVariance.variance fed the same x. Catches future drift between the two implementations.

Conventions

  • ruff format clean, ruff check clean.
  • Internal state, return values, and properties are all torch.Tensor on the user-supplied device, mirroring the dtype / device convention used elsewhere in ignite.metrics.
  • File is named _running_stats.py (leading underscore) and not re-exported from ignite/metrics/__init__.py, so it is internal to the metrics module. Public access stays through individual metric classes; the helper can graduate to a public API later if there is demand.

Test plan

  • [x] pytest tests/ignite/metrics/test_running_stats.py: 20 / 20 passing locally
  • [x] ruff format --check, ruff check
  • [ ] CI on this PR

cc @vfdev-5. Opening PR 2 (R2Score port) and PR 3 (PearsonCorrelation refactor on top of #3741) once this lands.

joemunene-by avatar May 11 '26 11:05 joemunene-by

Thanks for the review. Pushed 1b82442 addressing all three points.

1. No device / dtype in the helper. Dropped the constructor args and all internal .to(device) / .to(torch.float64) calls. State now takes the dtype and device of the first batch passed to update. Callers (R2Score, PearsonCorrelation) are responsible for the float64 upcast, which they were already doing in their own update methods anyway, so this is a no-op for the planned consumers and a cleaner contract for any future caller.

2. Dataclasses. Both classes are now @dataclass with field(default_factory=...) for the tensor fields. Dropped the manual __init__ and the reset() method; "reset" becomes reconstruction (self.welford = WelfordVariance()), which fits cleanly into how Metric.reset() is normally written in the consumer classes. Tests updated accordingly: test_reset is now test_fresh_instance_has_zero_state and just asserts the default-factory state.

3. Flatten. Removed the explicit .flatten() call. batch.mean() and batch.numel() already reduce over the full tensor regardless of shape, so the current scalar-reduction behavior is preserved and the code reads cleaner for any input shape.

On axis-aware reduction: the current consumers (R2Score, PearsonCorrelation) both produce a single scalar variance / covariance, so they only need the full-reduction behavior. If we want axis support for future per-channel use cases (running variance over (N, C, H, W) with reduction over (0, 2, 3)), the natural shape of the change is an optional dim parameter on update:

def update(self, batch: torch.Tensor, dim: Optional[Union[int, tuple[int, ...]]] = None) -> None:
    ...
    n_b = batch.numel() if dim is None else _samples_along(batch.shape, dim)
    mean_b = batch.mean(dim=dim, keepdim=False) if dim is not None else batch.mean()
    ...

The state on first update would take the shape of mean_b, and n_samples would become an int count of samples-per-position (still scalar because the reduction is the same at every position).

Two ways we can take it:

  • (a) Add the dim parameter in this PR so the helper ships fully-featured, even though no consumer uses it yet.
  • (b) Leave it scalar for now; add dim as a follow-up the first time a metric actually needs it (avoids speculative API surface).

I lean toward (b): the consumers don't need it, axis-aware running stats have a few subtleties (Bessel correction conventions, mixed-shape merge, axis reordering) that are easier to design alongside a concrete user. Happy to go either way; let me know which you prefer.

joemunene-by avatar May 11 '26 17:05 joemunene-by

@joemunene-by hi, I was trying to review but I find the code to be quite confusing I think we can try to make more readable :)

aaishwarymishra avatar May 13 '26 15:05 aaishwarymishra

@aaishwarymishra thanks, your inline points are all fair. Pushed e153f57 addressing each.

1. _zero() for a one-liner. Removed. Each tensor field now uses field(default_factory=lambda: torch.tensor(0.0)) directly. Six lines of one-purpose helper become six explicit defaults.

2. update's body duplicates merge. Refactored. update now builds a single-batch WelfordVariance from the input and calls self.merge(batch_acc). The Chan / Welford parallel formula now lives in exactly one place. Same refactor applied to WelfordCovariance.update (your "same here" on line 192).

The mental model that fell out of this is worth stating: update is the degenerate case of merge where the right-hand side has just been built from one batch. There's one formula, not two. I lifted that into the module docstring and the method docstrings so the next reader sees it immediately.

3. "Why do we need merge?" Distributed reduction. In multi-rank training, each rank accumulates its own WelfordVariance / WelfordCovariance over its local samples; at eval time the ranks fold their accumulators together rank-by-rank to produce the population statistic. Without an explicit merge, that cross-rank reduction has to re-iterate the raw data, which defeats the whole point of an online algorithm. I made this rationale explicit in merge's docstring (previously just one line, now a paragraph).

The bonus is that the two-path design (update for the local-batch case, merge for the cross-state case) collapses to a single formula at the implementation level, which I think also lands the "more readable" feedback from your top-level comment. Let me know if anything's still murky.

cc @vfdev-5 — points from your earlier review are still addressed in 1b82442; this commit is a follow-up to @aaishwarymishra's readability pass. Ready for another look when you have a moment.

joemunene-by avatar May 13 '26 17:05 joemunene-by

Copilot's auto-review surfaced four concrete points — pushed 89d5b36 addressing each:

  1. Docstring claimed the helpers were already used by PearsonCorrelation / R2Score. They aren't yet (that's PRs 2 and 3 of #3748). Reworded to "intended consumers (in follow-up PRs of #3748)" so the doc matches the state at this commit.
  2. Docstring claimed internal state in float64. It doesn't the helper is intentionally dtype/device agnostic per @vfdev-5's earlier review, and the caller supplies the float64 cast when stability matters. Realigned the prose so users don't read a false safety guarantee on float32 input.
  3. merge() lacked @torch.no_grad(). Both WelfordVariance.merge and WelfordCovariance.merge now have the decorator, matching update. A caller merging an accumulator whose tensors still carry grad would have built an autograd graph and leaked memory over time.
  4. cross_coef = n_a * n_b / n_ab precomputed as a Python float in WelfordCovariance.merge. Dropped the temporary, inlined n_a * n_b / n_ab directly into each parallel-formula line mirrors WelfordVariance.merge's existing style and keeps the arithmetic on the same dtype/device as the tensor operands.

20 / 20 tests still passing locally.

joemunene-by avatar May 14 '26 16:05 joemunene-by

The docstrings and comments are big and everywhere I think they can be made concise and removed which are not necessary.

Also I am not sure how the merge will work with sync_all_reduce can you give example.

aaishwarymishra avatar May 15 '26 11:05 aaishwarymishra

@aaishwarymishra thanks for the second pass. Pushed 1878aeb addressing each point:

1. "docstrings and comments are big and everywhere": agreed, they had grown past the point of useful. Trimmed roughly 60 lines from _running_stats.py (module + class + method docstrings) without losing the parallel-formula math or the rationale for merge. The 33-line module docstring is now 12 lines plus a code block for the distributed pattern.

2. "how the merge will work with sync_all_reduce": good question. The decorator defaults to dist.all_reduce(SUM), which is not the right operation for Welford state. The parallel formula is not a sum of per-rank means, so a plain SUM-reduce of the mean tensor across ranks would give the wrong combined mean. The pattern I'd reach for instead is all_gather of each rank's state followed by a local pairwise merge. Now written into the module docstring:

import ignite.distributed as idist

def compute(self):
    ws = self.welford
    if idist.get_world_size() > 1:
        n = idist.all_gather(torch.tensor([ws.n_samples]))
        m = idist.all_gather(ws.mean.reshape(1))
        s = idist.all_gather(ws.sum_sq_dev_from_mean.reshape(1))
        ws = WelfordVariance()
        for i in range(len(n)):
            ws.merge(WelfordVariance(int(n[i]), m[i], s[i]))
    return ws.variance

I held off on the actual distributed-aware metric wrapper in this PR because the consumer metrics (R2Score in PR 2, PearsonCorrelation in PR 3 of #3748) are where that lives most naturally. Happy to expose a _merge_all_ranks(welford) -> welford helper alongside the dataclasses if you'd prefer it sit one level lower.

3. "tests written as pure functions not classes": refactored. TestWelfordVariance / TestWelfordCovariance are gone; everything is now test_welford_variance_* / test_welford_covariance_* standalone functions, matching the style elsewhere under tests/ignite/metrics/.

4. "compares 1 step with external library baseline": added test_welford_variance_matches_numpy_at_each_step and the covariance equivalent. After every individual update the running stats are asserted against numpy's stats on the cumulative prefix, not just at end of stream. The covariance version also checks Pearson r against np.corrcoef at each step.

5. "no torch.clamp on line 290": intentional, and I should have flagged it more clearly in the first place. The variance properties clamp at zero because variance is non-negative by definition; the clamp guards against float rounding producing a tiny negative when all samples are equal. Covariance is legitimately signed (negative correlation gives negative covariance), so the same clamp would silently bias negatively-correlated pairs toward zero. I added an explicit docstring note on the property explaining the asymmetry, and a test_welford_covariance_negative_correlation_not_clamped regression that would fail if a future hand introduced the clamp.

23 tests passing locally. Ready for another look when you have a moment.

joemunene-by avatar May 15 '26 11:05 joemunene-by

@vfdev-5 what you think about this approach of using the merge in compute?

aaishwarymishra avatar May 16 '26 04:05 aaishwarymishra

2. "how the merge will work with sync_all_reduce": good question. The decorator defaults to dist.all_reduce(SUM), which is not the right operation for Welford state. The parallel formula is not a sum of per-rank means, so a plain SUM-reduce of the mean tensor across ranks would give the wrong combined mean. The pattern I'd reach for instead is all_gather of each rank's state followed by a local pairwise merge. Now written into the module docstring:

import ignite.distributed as idist

def compute(self):
    ws = self.welford
    if idist.get_world_size() > 1:
        n = idist.all_gather(torch.tensor([ws.n_samples]))
        m = idist.all_gather(ws.mean.reshape(1))
        s = idist.all_gather(ws.sum_sq_dev_from_mean.reshape(1))
        ws = WelfordVariance()
        for i in range(len(n)):
            ws.merge(WelfordVariance(int(n[i]), m[i], s[i]))
    return ws.variance

I held off on the actual distributed-aware metric wrapper in this PR because the consumer metrics (R2Score in PR 2, PearsonCorrelation in PR 3 of #3748) are where that lives most naturally. Happy to expose a _merge_all_ranks(welford) -> welford helper alongside the dataclasses if you'd prefer it sit one level lower.

I think we can just use the welford dataclass class state, something like

import ignite.distributed as idist

def compute(self):
    collected = idist.all_gather(self.welf)
    result = WelfordVariance()
        for item in collected:
            result.merge(item)
    return result.variance()

aaishwarymishra avatar May 20 '26 14:05 aaishwarymishra

@aaishwarymishra going with that. Double-checked _do_all_gather_object is wired through on NCCL (Gloo subgroup under the hood) so the object-gather path is safe for our case, just adds one pickle hop per compute() for our three small tensors. Negligible.

Two small fix-ups when it goes into the docstring:

def compute(self):
    if idist.get_world_size() > 1:
        collected = idist.all_gather(self.welford)
        merged = WelfordVariance()
        for item in collected:
            merged.merge(item)
        return merged.variance     # variance is a @property, not callable
    return self.welford.variance

(self.welford to match the existing field name in the consumer-side reference, and the inner indentation in your snippet was a copy-paste thing.)

Will push that into the module docstring next, with one line noting that consumers whose state is significantly larger than a few KB should prefer packing into a flat tensor before all_gather to skip the pickle hop. Anything else from this round you want bundled in?

joemunene-by avatar May 23 '26 23:05 joemunene-by

@vfdev-5 can you have a look it looks good to me and can be merged :)

aaishwarymishra avatar Jun 05 '26 19:06 aaishwarymishra

Hi @joemunene-by thank you for your effort , after discussing this pr we have some concerns .

  1. API doesn't fit ignite's conventions update() and merge() on a plain dataclass sits outside how ignite metrics are structured. Metrics use the Metric base class with the standard update() / compute() / reset() lifecycle. The helper needs to either fit that pattern or stay completely hidden as an implementation detail.
  2. DDP doesn't work with this approach The all_gather + pairwise merge pattern bypasses ignite's standard sync_all_reduce mechanism. This needs a tested solution that works within ignite's actual DDP setup, not just a docstring example.
  3. No end-to-end usage example The tests cover the helper in isolation. We need a concrete example — in the tests or PR description — showing this being used inside a real ignite metric, with the mean=1e6, std=1 failure case from #3662 demonstrating the fix.

Also it would be cleaner if you resolve the comment once it has been adderessed :)

aaishwarymishra avatar Jun 19 '26 19:06 aaishwarymishra

Thanks, all three addressed in b8fd9b61.

  1. Kept the helper private and pure (no Metric base, no distributed deps). To show it fits a real metric I added WelfordCorrelation in the tests: a minimal Metric over WelfordCovariance with the standard reset / update / compute lifecycle.
  2. You're right that sync_all_reduce(SUM) can't combine Welford state. The metric's compute() reduces by all_gather of each rank's state plus pairwise merge, and there's a TestDistributed that runs it across ranks and checks against the full gathered data. I also verified the merge on 2 gloo ranks offline: it matches numpy on the concatenated data to ~2e-16.
  3. test_welford_correlation_metric_recovers_3662_case drives the mean=1e6 case from #3662 through the metric and asserts the recovered r where the naive E[X^2]-E[X]^2 formula cancels in float32.

The multi-step-vs-baseline tests and the deliberate no-clamp on covariance are already in from the earlier round. Resolving the line threads now.

joemunene-by avatar Jun 19 '26 20:06 joemunene-by