Skip to content

FIX Stable diagonal covariance for float32 GaussianMixture - #34

Draft
ogrisel wants to merge 4 commits into
mainfrom
cursor/gmm-diag-covar-float32-4657
Draft

ogrisel wants to merge 4 commits into
mainfrom
cursor/gmm-diag-covar-float32-4657

Conversation

@ogrisel

@ogrisel ogrisel commented Nov 18, 2026 •

Copy link
Copy Markdown
Owner

Draft: this PR still requires self-review by @ogrisel before asking for reviews from others.

Reference Issues/PRs

Fixes scikit-learn#30382.

What does this implement/fix? Explain your changes.

GaussianMixture with covariance_type="diag" or "spherical" computes the per-component variance as E[X**2] - mean**2. For float32 data with a large feature magnitude relative to its spread, the two terms cancel. The result can be largely negative, which makes fit fail even with a generous reg_covar, or can be far above the true variance (for example, 112 instead of about 0 for X = [[9999], [0]]).

The change keeps the single-GEMM estimate as the fast path. A component is recomputed from the weighted second moment about its mean (the diagonal of the full-covariance estimator, which is already centered) when any feature has variance <= rel_tol * E[X**2], with rel_tol = 1e-2 for float32 and 1e-8 for float64.

The threshold is relative rather than absolute because the fast path's error is governed by variance / E[X**2], not by the variance alone.

Things to check in review:

  • Fallback is per component, so a component with many features is recomputed more often.
  • The unstable check and per-component loop add a host sync on array-API backends that are not NumPy. Only NumPy array-API tests were run locally.
  • Float32 at very large offsets (around 1e4 relative to the spread) is still inaccurate after the fix because component means come from a float32 GEMM in _estimate_gaussian_parameters, which this PR does not change.
  • nk is padded by 10 * eps, which slightly biases the fast path. This is unchanged.
  • Tied covariances have the same cancellation and are not changed here.

Changelog fragments are in doc/whats_new/upcoming_changes/sklearn.mixture/ and changed-models/, currently named 30382.*.rst after the issue. They need renaming to the upstream PR number once it exists, because towncrier uses that number.

Performance

Estimator timings, float32, 4-core VM:

  • Typical data (fast path): 0.97–1.03x the previous time.
  • Worst case, where every component falls back: 5–35x the previous time for the estimator alone.
  • End-to-end fit, 15 EM iterations: 1.00x at 100k x 10 x 10; 1.27x at 50k x 50 x 10 for diag/spherical. Always-centered computation would be about 2.6x.

Peak memory is unchanged from the previous estimator (one X-sized temporary).

Tests

  • test_estimate_diag_covariance_float32_large_magnitude: positivity and agreement with a float64 reference on float32 data near 1e4.
  • test_estimate_diag_covariance_matches_float64_reference: parametrized over offsets 0, 10 and 1e3, for float32 and float64. The offset-1e3 float32 case fails with the previous formula (relative error 2.4) and passes now (2.1e-6).
  • test_gaussian_mixture_collapsed_components_large_float32: fits the issue's [[9999], [0]] example for diag and spherical, in float32 and float64, and checks covariances are within 1e-3 of reg_covar.
  • test_gaussian_suffstat_sk_spherical: the per-component mean is now passed with shape (n_components, n_features), which is what the estimator expects.

Run with SKLEARN_RUN_FLOAT32_TESTS=1 and SCIPY_ARRAY_API=1 for the array-API cases: sklearn/mixture passes (155 passed, 224 skipped for unavailable backends).

AI usage disclosure

This pull request includes code written with the assistance of AI.
The code has not yet been reviewed by a human.

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Research and understanding
Open in Web Open in Cursor 

cursoragent and others added 3 commits November 18, 2026 09:21
Estimate diag and spherical variances as the weighted second moment
about the component mean. Subtracting mean**2 from E[X**2] cancels in
float32 and can be largely negative, so reg_covar cannot keep a
collapsed component valid.

Non-regression test for scikit-learngh-30382.

Co-authored-by: Olivier Grisel <[email protected]>
Without the explicit release, the previous iteration's buffer was still
alive while the next one was allocated, doubling the peak temporary.

Co-authored-by: Olivier Grisel <[email protected]>
Keep the single-GEMM E[X**2] - mean**2 estimate and recompute, from the
second moment about the mean, only the components whose variance falls
below a relative threshold of E[X**2] (1e-2 for float32, 1e-8 for
float64). Typical data keeps the previous speed; ill-conditioned
components get the stable estimate.

Non-regression test for scikit-learngh-30382.

Co-authored-by: Olivier Grisel <[email protected]>
Comment thread sklearn/mixture/_gaussian_mixture.py Resolved
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.

Gaussian Mixture: Diagonal covariance vectors might contain unreasonably negative values when the input datatype is np.float32

2 participants