Skip to content

FIX: prevent overflow in _incremental_mean_and_var - #35249

Closed
tatopenn-cell wants to merge 3 commits into
scikit-learn:mainfrom
tatopenn-cell:fix/standard-scaler-overflow
Closed

tatopenn-cell wants to merge 3 commits into
scikit-learn:mainfrom
tatopenn-cell:fix/standard-scaler-overflow

Conversation

@tatopenn-cell

Copy link
Copy Markdown

Fixes #5602.

What does this implement/fix?

StandardScaler.partial_fit keeps the cumulative sum of the samples
(last_sum = last_mean * last_sample_count) and the cross-term of the
variance. Both overflow on long streams or on values with a large
magnitude, and the mean becomes inf.

The fix keeps the cumulative-sum formula when it does not overflow
(it is more precise), and falls back to the delta-based update of Chan,
Golub and LeVeque (1979) when the cumulative sum overflows:

delta = new_mean - last_mean
updated_mean = last_mean + delta * new_count / total_count
updated_m2 = last_m2 + new_m2 + delta**2 * last_count * new_count / total_count

The formula is algebraically equivalent to the cumulative-sum one, but it
never reconstructs the sum. This is a deliberate deviation from a pure
replacement: a pure replacement of the mean formula with the delta-based
one loses precision on test_incremental_variance_numerical_stability.
The fallback is declared in the docstring of _incremental_mean_and_var.

The previous attempt (#11549) fixed the mean but left the variance
cross-term untouched, which is why it was closed. This PR fixes both.

The patch is written against the array API (xp), not np, so it keeps
working on the non-NumPy backends that _incremental_mean_and_var already
supports.

Tests

Two non-regression tests in sklearn/utils/tests/test_extmath.py:

  • test_incremental_mean_and_var_large_values_no_overflow: the
    reproducer of the issue. On main, the mean becomes inf. With the
    fix, it is finite and matches fit() within 1e-10.
  • test_incremental_mean_and_var_constant_values: constant data has
    variance 0, matching fit(). This is a regression check, not a proof
    of the fix: it passes on main too.

The first test fails on main (the mean is inf) and passes on this
branch.

Full suite: pytest sklearn/utils/tests/test_extmath.py -q -> 262
passed, 45 skipped.

Full analysis

The case study lives at
https://github.com/tatopenn-cell/Dense-Evolution-Discovery/tree/case/scikit-overflow/experiments/scikit_overflow
(full write-up, the paper, the numbers, the reference to Eq. 2.1a and
2.1b of STAN-CS-79-773).

The pytest failure on main is captured in
https://github.com/tatopenn-cell/Dense-Evolution-Discovery/blob/case/scikit-overflow/experiments/scikit_overflow/main_failure.txt

AI usage disclosure

I used an AI assistant to explore the code, run the experiments, and draft
the patch. I reviewed every line, ran the tests locally, and I can explain
every change. The delta-based update is Eq. 2.1b of Chan, Golub, LeVeque
(1979), page 4 of the Stanford tech report STAN-CS-79-773.

Any other comments

The _incremental_mean_and_var docstring already cites Chan, Golub, and
LeVeque. The change is in the same function the docstring describes.

The 4 ruff errors in extmath.py (lines 568, 775, 908, 998) and the 2
mypy errors (scipy stubs, Cython extension) are pre-existing on main
and are not introduced by this PR.

Tagging @lorentzenchr and @EdenRochmanSharabi for review.

The cumulative-sum formula reconstructs last_sum = last_mean *
last_sample_count and new_sum, both of which overflow on long
streams with large values. The delta-based update of Chan, Golub
and LeVeque (1979) is algebraically equivalent but never
reconstructs the sum.

This fixes the mean and the variance in one pass. The previous
attempt (scikit-learn#11549) fixed only the mean and left the cross-term of the
variance untouched, which is why it was closed as incomplete.

Two non-regression tests:
- test_incremental_mean_and_var_large_values_no_overflow
- test_incremental_mean_and_var_constant_values

Fixes scikit-learn#5602.
The cumulative-sum formula reconstructs last_sum = last_mean *
last_sample_count and new_sum, both of which overflow on long
streams with large values. The delta-based update of Chan, Golub
and LeVeque (1979) never reconstructs the sum.

The fix uses the cumulative-sum formula when it does not overflow,
and falls back to the delta-based update when it does. This keeps
the precision of the cumulative-sum formula on normal inputs (the
test_incremental_variance_numerical_stability test) and fixes the
overflow on large values (the issue scikit-learn#5602 reproducer).

Two non-regression tests:
- test_incremental_mean_and_var_large_values_no_overflow
- test_incremental_mean_and_var_constant_values

Fixes scikit-learn#5602.
ruff check on extmath.py reports a pre-existing set of errors
(lines 568, 775, 908, 998) and one new error introduced by this
PR at line 1289 (E501, 92 > 88). The new error is fixed here by
splitting the assignment across two lines. The pre-existing errors
are left untouched, to keep the scope clean.
@github-actions

Copy link
Copy Markdown

Thank you for opening your first pull request to scikit-learn! 🎉

To help get your contribution reviewed, please make sure that:

  • You have filled out the pull request template.

  • The pull request addresses an existing issue that is ready for contribution (e.g. not tagged as 'Needs Triage', 'Needs Decision', ...). If you are proposing a new feature, please open an issue to discuss it first.

  • There are no other open pull requests already targeting the same issue.

  • You have followed the pull request checklist. In particular, linting and tests should pass.

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Oct 27, 2026
@github-actions

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


ruff check

ruff detected issues. Please run ruff check --fix --output-format=full locally, fix the remaining issues, and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

sklearn/utils/tests/test_extmath.py:4:1: I001 [*] Import block is un-sorted or un-formatted
   |
 2 |   # SPDX-License-Identifier: BSD-3-Clause
 3 |
 4 | / import itertools
 5 | |
 6 | | import numpy as np
 7 | | import pytest
 8 | | from scipy import linalg, sparse, stats
 9 | | from scipy.linalg import eigh
10 | | from scipy.sparse.linalg import eigsh
11 | |
12 | | from sklearn import config_context
13 | | from sklearn.preprocessing import StandardScaler
14 | | from sklearn.datasets import make_low_rank_matrix, make_sparse_spd_matrix
15 | | from sklearn.utils import gen_batches
16 | | from sklearn.utils._arpack import _init_arpack_v0
17 | | from sklearn.utils._array_api import (
18 | |     _max_precision_float_dtype,
19 | |     array_device,
20 | |     get_namespace,
21 | |     move_to,
22 | |     yield_namespace_device_dtype_combinations,
23 | | )
24 | | from sklearn.utils._testing import (
25 | |     _array_api_for_tests,
26 | |     assert_allclose,
27 | |     assert_allclose_dense_sparse,
28 | |     assert_almost_equal,
29 | |     assert_array_almost_equal,
30 | |     assert_array_equal,
31 | |     skip_if_32bit,
32 | | )
33 | | from sklearn.utils.extmath import (
34 | |     _approximate_mode,
35 | |     _deterministic_vector_sign_flip,
36 | |     _incremental_mean_and_var,
37 | |     _randomized_eigsh,
38 | |     _safe_accumulator_op,
39 | |     cartesian,
40 | |     density,
41 | |     randomized_range_finder,
42 | |     randomized_svd,
43 | |     row_norms,
44 | |     safe_sparse_dot,
45 | |     softmax,
46 | |     stable_cumsum,
47 | |     svd_flip,
48 | |     weighted_mode,
49 | | )
50 | | from sklearn.utils.fixes import (
51 | |     COO_CONTAINERS,
52 | |     CSC_CONTAINERS,
53 | |     CSR_CONTAINERS,
54 | |     DOK_CONTAINERS,
55 | |     LIL_CONTAINERS,
56 | |     _sparse_random_array,
57 | | )
   | |_^ I001
   |
   = help: Organize imports

Found 1 error.
[*] 1 fixable with the `--fix` option.

ruff format

ruff detected issues. Please run ruff format locally and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

--- sklearn/utils/extmath.py
+++ sklearn/utils/extmath.py
@@ -1221,9 +1221,7 @@
                 xp.zeros_like(xp.asarray(last_mean, dtype=max_float_dtype)),
             )
             delta_mean = last_mean + delta * new_sample_count / updated_sample_count
-            updated_mean = xp.where(
-                xp.isfinite(updated_mean), updated_mean, delta_mean
-            )
+            updated_mean = xp.where(xp.isfinite(updated_mean), updated_mean, delta_mean)
 
         if last_variance is None:
             updated_variance = None
@@ -1245,9 +1243,7 @@
             else:
                 correction = _safe_accumulator_op(sum_op, temp, axis=0)
                 temp **= 2
-                new_unnormalized_variance = _safe_accumulator_op(
-                    sum_op, temp, axis=0
-                )
+                new_unnormalized_variance = _safe_accumulator_op(sum_op, temp, axis=0)
 
             new_unnormalized_variance -= correction**2 / new_sample_count
 
@@ -1286,9 +1282,9 @@
                     * new_sample_count
                     / updated_sample_count
                 )
-                updated_unnormalized_variance_safe[zeros] = (
-                    new_unnormalized_variance[zeros]
-                )
+                updated_unnormalized_variance_safe[zeros] = new_unnormalized_variance[
+                    zeros
+                ]
                 updated_variance_safe = (
                     updated_unnormalized_variance_safe / updated_sample_count
                 )
@@ -1300,6 +1296,7 @@
 
     return updated_mean, updated_variance, updated_sample_count
 
+
 def _deterministic_vector_sign_flip(u):
     """Modify the sign of vectors for reproducibility.
 

--- sklearn/utils/tests/test_extmath.py
+++ sklearn/utils/tests/test_extmath.py
@@ -1200,8 +1200,7 @@
 
     iscaler = StandardScaler()
     for i in range(0, 1000, 10):
-        iscaler = iscaler.partial_fit(X[i:i + 10])
+        iscaler = iscaler.partial_fit(X[i : i + 10])
 
     assert_allclose(iscaler.mean_, scaler.mean_, rtol=1e-12)
     assert_allclose(iscaler.var_, scaler.var_, atol=1e-15)
-

2 files would be reformatted, 961 files already formatted

Generated for commit: 038beaf. Link to the linter CI: here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Linter failure The linter CI is failing on this PR module:utils size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: StandardScaler partial_fit overflows

1 participant