Skip to content

PRF Ridge - centering trick for cholesky solver - #34793

Open
cakedev0 wants to merge 27 commits into
scikit-learn:mainfrom
cakedev0:ridge/optim_cholesky
Open

cakedev0 wants to merge 27 commits into
scikit-learn:mainfrom
cakedev0:ridge/optim_cholesky

Conversation

@cakedev0

@cakedev0 cakedev0 commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

None, I started investigating for a speed gain while comparing speed/profiles with the scikit-learn-intelex (oneDAL) implementation.

Numerical stability discussions here led to #35029 (GLMs on off-centered data) and #35030 (an alternative with an a priori mean/variance check).

What does this implement/fix? Explain your changes.

  • For float64 X, _solve_cholesky centers the Gram matrix algebraically (Xc.T @ Xc = X.T @ X - n_samples * outer(X_offset, X_offset)) instead of materializing a centered copy of X. It only applies to the primal branch (n_samples >= n_features) without sample weights.
  • It refactors a bit the validation to avoid a double pass of check_array (and to avoid a copy in the algebraic centering path).

Those relatively simple changes give speed-ups ranging from ~1.2x to 2x, and save a copy of X (e.g. 2GB of RAM for a 2GB X).

Numerical stability. The algebraic centering loses precision for features with a large mean/std ratio r: the error on coef_ grows like eps * r**2 * cond, against eps * cond for explicit centering (cond being the condition number of the centered Gram matrix). When the cancellation is bad enough to make the Gram matrix non positive definite, Cholesky fails and we fall back to the svd solver on an explicitly centered X, as on main.

Relative error on coef_ (n=20000, p=20, OpenBLAS, my laptop):

r well-conditioned, main well-conditioned, this PR strongly correlated features (cond ~2e7), main strongly correlated features, this PR
1e2 3e-15 1e-10 1e-9 2e-5
1e3 3e-15 4e-8 2e-9 2e-3
1e4 2e-14 1e-6 9e-10 1e-1
1e5 9e-14 3e-4 3e-9 svd fallback

In float32, the same trick already gives ~6e-4 at r=10 and ~5e-2 at r=100 on well-conditioned data, so float32 X keeps the explicit centering.

For float64, I think this degradation is acceptable: it needs both a large offset and strongly correlated features to matter, and GLMs (LogisticRegression, PoissonRegressor, ...) already return wrong coefficients without warning from r ~100-300 in float64 (see #35029). If we want to go further, #35030 implements an a priori mean/variance check that could decide between the two centerings.

AI usage disclosure

I used AI assistance for:

  • Code generation (many iterations)
  • Comments
  • Research and understanding
  • Numerical stability experiments

Benchmarks

Benchmarks are run through the PR: probabl-ai/scikit-learn-benchmarks#31 (see bot comments with links to dashboards)

The benchmark cases are the same as the ones used to compare with scikit-learn-intelex, they are a mix of synthetic and real-world datasets.

On the intel-laptop, one case shows a regression but it's a benchmark artifact: this case uses the dual path, which is not affected by this PR. And if you look at the granular timings, you'll see both branches (main and this one) oscillate a lot.

@cakedev0 cakedev0 changed the title PRF Ridge - centering trick & fast mean & fast assert finite [WIP] PRF Ridge - centering trick & fast mean & fast assert finite Aug 21, 2026
… to svd

use_no_center_cholesky matched on solver in ("auto", "cholesky") but didn't
check the array namespace. With array API dispatch to a non-numpy namespace,
solver="auto" silently resolves to "svd" instead of "cholesky" (see
resolve_solver), which needs X to actually be centered. This left X
uncentered while running svd, causing
test_cross_val_predict_array_api_compliance[...-Ridge] failures on
array_api_strict and torch in CI.
@cakedev0 cakedev0 changed the title [WIP] PRF Ridge - centering trick & fast mean & fast assert finite [WIP] PRF Ridge - centering trick Aug 25, 2026
Comment on lines +396 to +399
elif is_X_sparse and fit_intercept:
# when `fit_intercept=True`, `mean_variance_axis` will be called on X
# and it requires csr/csc format
return ["csr", "csc"]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note to reviewers: this addition is needed because I now pass check_input=False to _preprocess_data which would have done this logic.

@cakedev0 cakedev0 changed the title [WIP] PRF Ridge - centering trick PRF Ridge - centering trick for cholesky solver Aug 27, 2026
@cakedev0
cakedev0 marked this pull request as ready for review August 27, 2026 06:55
@cakedev0

Copy link
Copy Markdown
Member Author

cc @antoinebaker, I was told you're the specialist of this kind of tricks 😉

@cakedev0 cakedev0 moved this to PR waiting for reviews in Labs Aug 31, 2026
@cakedev0 cakedev0 added this to Labs Aug 31, 2026
@cakedev0

cakedev0 commented Aug 31, 2026 •

Copy link
Copy Markdown
Member Author

I checked memory usage and I did see it saving 2GB of RAM of a X of 2GB (which is expected as it avoids a copy). I guess this is a nice improvement, as memory might be a limit more often than run time for this model that usually is very fast.

Edit: Hum... I just had an OOM caused by Ridge on main while running benchmarks... 😄

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The centering and validation optimizations look good to me but I don't understand the change related to the solvers.

Also please add a changelog entry.

Comment thread sklearn/linear_model/_ridge.py Resolved
Comment thread sklearn/linear_model/_ridge.py Resolved
@ogrisel ogrisel moved this from PR waiting for reviews to In progress in Labs Sep 7, 2026
@cakedev0 cakedev0 moved this from In progress to PR waiting for reviews in Labs Sep 7, 2026
@antoinebaker

Copy link
Copy Markdown
Member

The second one would be more complex (requires careful Cython implementation of some kind of mean_variance_axis(X, axis)), but a bit "cleaner" because it would be an "a priori" check.

What about simply computing the mean and variance for the a priori check, eg with numpy ?

@lorentzenchr

Copy link
Copy Markdown
Member

How about this: Let's avoid centering for _solve_cholesky altogether and compute the hessian/gram as if we added the intercept as the last column of X, i.e. w = np.concat((coef, [intercept])). This is what LinearModelLoss does as used for GLMs like LogisticRegression.
This avoids memory copies as well as numerical instabilities. In fact, if it were for 1-d targets only, we could just use LinearModelLoss(base_loss=HalfSquaredError()).

@cakedev0

Copy link
Copy Markdown
Member Author

This approach has the same cancellation issue than what I proposed. It just happens in LAPACK instead of in numpy. But this "intercept as last column" approach has the big advantage to raise a LinAlgWarning when relevant, which to me makes this centering trick acceptable without a guard (the warnings already serves as a soft guard). => I implemented that.

Thank you for the idea @lorentzenchr!


Still, this shows GLMs currently suffer from the issue we're afraid of introducing in Ridge and it could motivate working on the "a priori check" in a future PR:

  • in Ridge, we would use it to decide if we do this "implicit centering" or not.
  • in GLMs we could use it to do explicit centering for solvers where it's possible.

@cakedev0

Copy link
Copy Markdown
Member Author

I reran the benchmarks and performance gain is still there, same as before 👍

@lorentzenchr

Copy link
Copy Markdown
Member

Still, this shows GLMs currently suffer from the issue

I don’t think so.
GLM (gaussian case):

H = [X, 1]' [X, 1]
  = [X'X, X'1]
    [1'X, 1‘1]

This is a (p+1)^2 matrix. I don’t see any danger of catastroohic cancellation.

Ridge (and Lasso) uses:

H = (X - 1/n 11'X)' (X - 1/n 11'X)

This is a p^2 matrix. Cancellation can happen depending on the way this is computed.

@antoinebaker

antoinebaker commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

The CI is failing on test_ridge_regression_unpenalized_hstacked_X for the random seed 7. Could you run linear_model/tests/test_ridge.py for all random seeds ?

@cakedev0

cakedev0 commented Sep 23, 2026 •

Copy link
Copy Markdown
Member Author

Indeed the test is failing for some seeds (the proportion of failing seed might vary depending on the BLAS implementation).

Claude says:

_solve_cholesky's augmented [X, 1] Gram matrix is built from raw, uncentered X. For any column with mean μ and std σ, this inflates the Gram matrix's magnitude by a factor of 1 + (μ/σ)² relative to the old centered Gram matrix — in the failing test the intercept-like column (σ=0) makes this extreme (max entry 12.0 vs 0.98 for the old centered Gram). That extra magnitude eats into the precision of the rounding noise sitting right on top of the near-zero eigenvalue that the duplicated columns create, which is exactly the threshold LAPACK's dpotrf/dpocon use to decide singular vs. ill-conditioned vs. fine.

And it doesn't even raises a warning, so I can't catch it and fallback to svd or whatever... This probably invalidates this approach...

Note that the previously implemented "algebraic centering trick" did not suffer from this issue (but I'm not sure why).


@lorentzenchr

this shows GLMs currently suffer from the issue
I don’t think so.

It does happen, here is a failing test proving it: #35023


I think the next step should be either:

  • reverting to the initial centering trick and accepting the numerical stability degradation (maybe gating on float64 so it's unlikely to impact any user)
  • giving a try a the "a priori check" (mean & variance calculation in a single data pass, doing it in to data pass would eat the speedup of this PR - but not memory footprint reduction). This could be useful for GLMs too.

@lorentzenchr

Copy link
Copy Markdown
Member

I am not convinced by the AI explanation.

Can someone try

  • fit time bench
  • num stability bench
  • on current main Ridge cholesky, this PR Ridge cholesky and TweedieRegressor(solver=newton-cholesky)

@ogrisel

ogrisel commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

I think the next step should be either:
reverting to the initial centering trick and accepting the numerical stability degradation (maybe gating on float64 so it's unlikely to impact any user)
giving a try a the "a priori check" (mean & variance calculation in a single data pass, doing it in to data pass would eat the speedup of this PR - but not memory footprint reduction). This could be useful for GLMs too.

I think I would like to see the later option implemented in an alternative PR (while keeping the current implementation of this PR here) to be able to experiment more with both options and assess there ability to deal robustly with the low regularized under-determined regime.

I suspect that the current state of this PR fails to converge to the minimum norm solution in the lowly regularized regime on an underdetermined problem.

@ogrisel

ogrisel commented Sep 24, 2026

Copy link
Copy Markdown
Member

Note that the previously implemented "algebraic centering trick" did not suffer from this issue (but I'm not sure why).

This looks related to the work we started a while ago to investigate the conditions to continously converge to the minimum norm OLS solution when alpha goes to 0.

In my earlier experiments I observed a discontinuity in the solution space when using the "column-of-1" trick to implement the intercept:

#25948 (comment)

This reverts commit f5ed039.
@cakedev0

cakedev0 commented Sep 25, 2026 •

Copy link
Copy Markdown
Member Author

So:

cakedev0 and others added 2 commits September 25, 2026 09:36
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This reverts commit 7d2ab87, pushed to this branch by mistake.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The algebraic centering of the Gram matrix loses about 2 * log10(mean/std)
digits compared to explicit centering, which float32 cannot afford.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cakedev0

cakedev0 commented Oct 8, 2026

Copy link
Copy Markdown
Member Author

Given the discussion in #35029, I'd like to move forward with this PR, but only for float64 X (float32 keeps the explicit centering). This is what this PR currently implements.

For float64, this trick remains stable until mean/variance ratio reaches ~1e6. For comparison, GLMs already return wrong coefficients without any warning from a ratio of 100-300 in float64 (#35029).

If we want to remove the remaining degradation, #35030 has an a priori mean/variance check that could decide between the two centerings, but I'd rather discuss it there or in issue #35029 and keep this PR simple.

cc @lorentzenchr (you raised the cancellation issue) @ogrisel (you approved before it came up) @antoinebaker. WDYT?

@antoinebaker

Copy link
Copy Markdown
Member

I'm fine with the approach (restrict to float64, no a-priori check). I feel it's a good compromise between the code complexity (I am not a big fan of the proliferation of helper functions and API changes to _preprocess_data in the AI generated PRs) and the performance gain (time and memory). I guess the float32 use-case is rather niche anyway ?

Comment thread sklearn/linear_model/_ridge.py Resolved
@cakedev0 cakedev0 moved this from PR Stalled to PR waiting for reviews in Labs Oct 20, 2026
@cakedev0 cakedev0 moved this from PR waiting for reviews to PR Stalled in Labs Nov 2, 2026
cakedev0 added a commit to cakedev0/my-scikit-learn-backlog that referenced this pull request Nov 3, 2026
done: HGB: get [sklearn#35216](scikit-learn/scikit-learn#35216) merged (binning crash on all-missing features, fixes [sklearn#35164](scikit-learn/scikit-learn#35164)), merged before I removed it
done: Trees: get [sklearn#34554](scikit-learn/scikit-learn#34554) merged (recursion PDP on categorical features)
drop: Threads: answer lesteve on [sklearn#35105](scikit-learn/scikit-learn#35105) (RFC deprecate `pre_dispatch`)
drop: Maintenance: follow up on [sklearn#35209](scikit-learn/scikit-learn#35209) (newton-cg test failing on the macOS x86_64 wheels)
drop: Benchmarks: review [benchmarks#142](probabl-ai/scikit-learn-benchmarks#142) (cuML benchmark config)
drop: Threads: review [sklearn#34729](scikit-learn/scikit-learn#34729) (inference methods don't modify the estimator)
drop: Linear: [sklearn#34793](scikit-learn/scikit-learn#34793) (Ridge centering trick for cholesky), benchmarks in [benchmarks#115](probabl-ai/scikit-learn-benchmarks#115) and [benchmarks#31](probabl-ai/scikit-learn-benchmarks#31)
drop: Upstream: sklearnex reports [sklearnex#3402](uxlfoundation/scikit-learn-intelex#3402), [sklearnex#3377](uxlfoundation/scikit-learn-intelex#3377), [sklearnex#3220](uxlfoundation/scikit-learn-intelex#3220)
drop: Upstream: [data-apis/array-api#976](data-apis/array-api#976) (why `stable=True` is the default for `xp.sort`)
drop: Upstream: dpnp reports [IntelPython/dpnp#3149](IntelPython/dpnp#3149) and [IntelPython/dpnp#3148](IntelPython/dpnp#3148)
drop: Threads: [sklearn#34736](scikit-learn/scikit-learn#34736) (oversubscription in `pairwise_distances`), out of the reported findings item
drop: KMeans: benchmarks [benchmarks#154](probabl-ai/scikit-learn-benchmarks#154), [benchmarks#160](probabl-ai/scikit-learn-benchmarks#160), [OpenBLAS#6105](OpenMathLib/OpenBLAS#6105) and [sklearn#17334](scikit-learn/scikit-learn#17334), out of the [sklearn#35193](scikit-learn/scikit-learn#35193) item
todo: move [joblib#1899](joblib/joblib#1899), [sklearn#35261](scikit-learn/scikit-learn#35261) and [sklearn#35053](scikit-learn/scikit-learn#35053) from Reviews to Now, [sklearn#35181](scikit-learn/scikit-learn#35181) to the top of Waiting (by hand in 03835dd)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants