Skip to content

FIX Sparse coordinate descent diverges on constant columns - #40

Closed
cakedev0 wants to merge 2 commits into
mainfrom
fix/sparse-cd-constant-column
Closed

cakedev0 wants to merge 2 commits into
mainfrom
fix/sparse-cd-constant-column

Conversation

@cakedev0

@cakedev0 cakedev0 commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

Reference Issues/PRs

Draft on my fork, before opening it upstream.

Found through the red CI of scikit-learn#34339: it adds sparse X to test_glm_regression_unpenalized_hstacked_X, whose X has a column of ones when fit_intercept=True, and newton-cd diverges on it for ~4% of the seeds. The bug is already on main, sparse X just wasn't tested there.

What does this implement/fix? Explain your changes.

newton-cd diverges on sparse X with a constant column and an intercept:

import numpy as np
import scipy.sparse as sp
from sklearn.linear_model import PoissonRegressor

rng = np.random.RandomState(55)
X = rng.randn(12, 3)
y = rng.poisson(np.exp(X @ [0.3, -0.2, 0.1] + 0.5))
X = np.c_[X, np.ones(12)]  # constant column, with fit_intercept=True
params = dict(alpha=0, solver="newton-cd", tol=1e-12, max_iter=1000)
print(PoissonRegressor(**params).fit(X, y).coef_)
# [ 0.02760118 -0.48354333  0.0384222   0.        ]
print(PoissonRegressor(**params).fit(sp.csr_matrix(X), y).coef_)
# main:      [ 4.32760281e+276 -4.04219263e+275 -3.81870078e+276  7.60914118e+292]
# this PR:   [ 0.02760118 -0.48354333  0.0384222   0.        ]

For sparse X, coordinate descent centers implicitly, with X_mean passed on the side. With sample weights, R_and_X_colnorm2_sparse computed the centered squared norm of a column as sum_nz(sw * (x - m)**2 - sw * m**2) + sw_sum * m**2, which cancels catastrophically. For a constant column, the norm should be 0 but it isn't. The formula alone gives a nonzero norm even when m is exactly 1 (266/1000 random weights, 12 samples). In real fits m is only accurate up to rounding as well: on 300 newton-cd fits with 100 samples, it isn't exactly 1 in 7667/7759 calls and the norm isn't 0 in 7582/7759 calls, typically a few 1e-15 and sometimes negative. Coordinate descent only skips a column whose norm is exactly 0, so it updates this one by dividing a rounding error by another, and the coefficients blow up within one call.

The fix is in a helper now shared with R_and_X_colnorm2_multi_task, which had the same formula:

  • Compute the norm without cancellation: sum_nz(sw * (x - m)**2) + (sw_sum - sw_nz_sum) * m**2, the second term only when the column has implicit zeros.
  • Return 0 when the variance is under the rounding bound of sklearn.preprocessing._data._is_constant_feature (the one StandardScaler uses), except that it uses FLT_EPSILON for float32 where _is_constant_feature always uses the float64 eps. See the known problem below.

Both are needed. On 200 newton-cd fits with sparse X and a constant column, 23 diverge or differ from dense X on main, 27 with the first change only, and 0 with both.

Sparse Lasso and ElasticNet diverge too, with alpha=0 and sample_weight. Without sample_weight I saw no wrong fit (0/500 for Lasso). On 100 seeds with 100 samples, Linux x86-64:

1.9.1 main this PR
PoissonRegressor(alpha=0, solver="newton-cd") 12/100 wrong, max abs(coef) 1.8e288 0/100
LogisticRegression(C=np.inf, solver="newton-cd") 8/100 wrong, max abs(coef) 2.7e293 0/100
Lasso(alpha=0) 43/100 wrong, max abs(coef) 2.0e306 8/100 wrong, max abs(coef) 4.3e189 0/100

The newton-cd-csr_matrix cases of test_glm_regression_unpenalized_hstacked_X from scikit-learn#34339 (all seeds) fail 37/1600 times on main and 0/1600 with this PR.

Known problem, to fix before opening this upstream

The bound also catches real columns, and this is a regression on float32. With float32, a column of mean 1 and std 0.05, and 1M samples, Lasso(alpha=1e-6) gives a coef of 20.0 on main (same as dense) but 0 with this PR, with a ConvergenceWarning:

import numpy as np
import scipy.sparse as sp
from sklearn.linear_model import Lasso

n = 1_000_000
rng = np.random.RandomState(0)
x = 1 + 0.05 * rng.randn(n)  # not constant: 5% relative std
X = np.c_[x, rng.randn(n)].astype(np.float32)
y = ((x - x.mean()) / 0.05 + 0.1 * rng.randn(n)).astype(np.float32)
print(Lasso(alpha=1e-6).fit(X, y).coef_)
# [ 1.9997982e+01 -1.4122413e-04]
print(Lasso(alpha=1e-6).fit(sp.csc_array(X), y).coef_)
# main:    [ 1.9997875e+01 -1.4122047e-04]
# this PR: [0.         0.00047986]

The bound grows with (n_samples * mean * eps)**2, so it triggers when std / mean < n_samples * eps.

Not a regression: the same kind of float64 column is already wrong on main (0 instead of ~9e4 for mean 1e6, std 1e-5, 1M samples), and a sparse float32 Poisson fit on a low-variance column is wrong on both (-1.9e14 on main, 0 with this PR, 29.9 on dense).

Pending decision: how to fix this. Using the float64 eps in the bound wouldn't catch float32 constant columns, so there are two options:

  • Replace the bound with an exact check: a column is constant only if all its stored values are equal and it has no implicit zeros. No threshold, so it can't catch real columns, but a column that's constant only up to rounding noise isn't skipped. Not implemented or tested yet.
  • Tune the bound, which keeps the risk of catching real columns.

I'd go for the exact check.

Any other comments?

The same cancellation (sum of squares minus n * mean**2) is in other places, not fixed here. It loses ~eps * (mean / std)**2 in relative precision, so it shows on features with a large offset:

AI usage disclosure

I used AI assistance for:

  • Code generation (Claude Code, I reviewed it)
  • Research and understanding (finding the root cause)

🤖 Generated with Claude Code

The centered column norm cancelled catastrophically: for a constant column,
whose mean is only accurate up to rounding, it was a tiny positive or even
negative value instead of 0, and coordinate descent diverged on it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cakedev0 added a commit to cakedev0/my-scikit-learn-backlog that referenced this pull request Nov 3, 2026
todo: move [sklearn#35295](scikit-learn/scikit-learn#35295) from Now to Waiting, lorentzenchr's review addressed
todo: [fork#40](cakedev0/scikit-learn#40) is the fix for the red CI of [sklearn#34339](scikit-learn/scikit-learn#34339), waiting on lorentzenchr

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

@lorentzenchr lorentzenchr left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Could you check if this has a small performance impact, in particular on the multitask lasso? (super simple benchmark is sufficient)

Comment thread sklearn/linear_model/_cd_fast.pyx 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.

2 participants