Repository navigation
Conversation
L-BFGS optimizes over v = s * coef and c = intercept + coef @ m, with m the column means and s = max(1, std), without copying X. It fixes lbfgs stopping far from the optimum on offset features (scikit-learngh-35029) and silently returning the starting point when its first step overflows the loss. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The full pass over dense X cost ~3 loss/gradient evaluations and made a float64 copy of float32 X. Also update the gradient in place, without transposed copies for multiclass. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Reference Issues/PRs
Towards scikit-learn#35029. Draft on my fork, to discuss before opening it upstream.
What does this implement/fix? Explain your changes.
lbfgsinLogisticRegression,PoissonRegressor,GammaRegressorandTweedieRegressor(and thelbfgsfallback of the Newton solvers) now runs on implicitly centered and scaled columns. L-BFGS optimizes overv = s * coefandc = intercept + coef @ m, withmthe column means (only with an intercept) ands = max(1, std).Xis never copied, sparseXstays sparse, and the penalty stays oncoef, so the problem and its minimizer don't change, whatever the values ofmands. It's a wrapper aroundLinearModelLoss.loss_gradient(_LBFGSReparametrizationin_linear_loss.py). For denseX,mandsare estimated on at most 10k evenly spaced rows: on all rows, it cost ~3 loss/gradient evaluations (see Benchmarks). For sparseX, it's one call tomean_variance_axis. Then each evaluation costs O(n_classes * n_features) more.It fixes two ways
lbfgssilently stops far from the optimum:coef_was 71% to 100% off from offset 1e3 in float64. It's now within 0.03% forLogisticRegressionandPoissonRegressor, in 5 or 6 iterations.GammaRegressor()returned the intercept-only model after 1 iteration. It now converges in 3 iterations tonewton-cholesky's solution:I found the second one benchmarking the GLM solvers against glum on real data, with target-encoded columns (in the thousands) of a Gamma model on freMTPL2 claim amounts:
lbfgsstopped ~2% above the optimum at anytol.tol: L-BFGS-B'sgtolapplies to the gradient with respect to(v, c), which is the gradient with respect tocoefdivided bys. Sogtol = tol / max(s), which keepsmax |gradient| <= tolforcoefwithout an intercept. Without that,lbfgsstopped 4x to 10x further from the optimum at the defaulttolintest_logistic_regression_solvers. With an intercept, the centered gradient is used on purpose: the uncentered one is what's small far from the optimum on offset features.The price is that the number of iterations depends on the units of the largest column. With 200 one-hot columns and a standard normal column multiplied by 1e4, the problem in
(v, c)is the same as without the 1e4, butPoissonRegressortakes 61 iterations instead of 25 (LogisticRegression: 56 instead of 15), becausegtolis 1e4 times smaller. Withgtol = tol, it takes 13 to 19 iterations andcoef_is as close to the optimum as on the problem without the 1e4, butmax |gradient|forcoefcan then be up tomax(s) * tol. I kept the stricter rule, WDYT?Alternatives
I compared 4 choices of
sin a prototype (scipy's L-BFGS-B on the same objective, outside scikit-learn), on 5 real problems (logistic regression on bank_marketing, kick and kddcup09_churn, Poisson and Gamma GLMs on freMTPL2, with spline and one-hot features in [0, 1] and target-encoded columns) and on the sweep of scikit-learn#35029. Iterations to reachtol=1e-8, on one NUMA node of a Xeon 6787P:main)s = 1)s = std)s = sqrt(var + alpha)s = max(1, std)(this PR)smakes the penalty badly conditioned inv. glum's ownlbfgsdoes the same there (glum 3.4.1 with scipy 1.16): 12,548 iterations and still 1.7e-2 above the optimum. glum's IRLS solvers are fine, as Newton steps don't depend on a diagonal rescaling.sqrt(var + alpha)bounds the penalty's curvature invby 1. It's safe everywhere and doesn't depend on the units, but up to 2.2x slower than centering where centering is enough.max(1, std)is the same as centering on these 4 problems (all their columns have a std <= 1) and fixes the large-scale case. But the threshold of 1 depends on the units of the features, and I picked it after seeing these problems, so it's partly fitted to them. It does nothing for columns with a small scale. A test on raw numeric features in very different units would tellmax(1, std)andsqrt(var + alpha)apart, I haven't run it yet.This is close to scikit-learn#15583 (
lbfgspreconditioned by the std inLogisticRegression, closed). Its counter-examples were MNIST / 255 and low-rank data with 2 columns multiplied by 1e3, where it took more iterations. Withs = max(1, std), this PR needs 2.4x to 3.4x fewer iterations on the first attol=1e-8. On the second, it's mixed: fewer iterations withC=1000andC=0.001, more withC=1. See Benchmarks.Other options, not exclusive with this one:
tolafter L-BFGS-B returns and warn if it isn't met, whatever the status. In the BUG: LogisticRegression (and other GLMs) can silently return badly wrong coefficients on off-centered data scikit-learn/scikit-learn#35029 sweep, it flags 12 of the 14 bad fits (those that stop on "relative reduction of f"), but not the 2 where the gradient check passes withcoef_71% off. Cheap, I think it's worth adding as a safety net either way.newton-choleskywhen that check fails. It costs a second fit and doesn't help wide problems.Benchmarks
On a laptop (Intel Core Ultra X7 358H, 16 threads),
mainand this branch interleaved with idle time in between, median of 3 to 5 fits, default parameters unless said otherwise. The scripts are not in the repo, I can share them.TLDR:
mainwithin ~15% either way.C=100, the branch takes fewer iterations and is 7% to 9% faster overall, withC=1it is 4% to 7% slower.tol, and 2.4x to 3.4x fewer iterations attol=1e-8, to the same objective.Synthetic data where both converge quickly (500k x 100 dense standard normal, 500k x 2000 sparse with density 0.01):
Computing
mandson all the rows of this denseXtook 62-70 ms in float64, and 121-131 ms in float32 becausesw @ XcastXto float64. That made these fits ~15% to 2.2x slower, hence the subsample.LogisticRegressiononfetch_20newsgroups_vectorized(subset="train")(11314 x 130107 sparse, 20 classes):LogisticRegression(max_iter=1000)on the first 20k rows of MNIST / 255 (10 classes), and on the low-rank data of scikit-learn#15583 (1000 x 10000,make_low_rank_matrixwith 2 columns multiplied by 1e3):With
tol=1e-8, MNIST takes 284 -> 84 iterations (C=0.01) and 812 -> 336 (C=1), and the low-rank data 197 -> 158 (C=1000) and 18 -> 24 (C=1). At the defaulttol, both stop at a different distance from the optimum: on the low-rank data withC=1000,mainstops 1.7% above it and this branch 4.9%; withC=1,mainstops 3.6e-4 above it (relative) and this branch 3e-7.Any other comments?
Tests: a unit test of the change of variables (exact chain rule, dense and sparse, with and without intercept and sample weights), a test of the subsampled mean and variance, and non-regression tests for both cases above. They fail on
mainand pass here. The rest ofsklearn.linear_modeland the common checks of these estimators pass, except 2 tests, which I haven't changed:test_logistic_regressioncv_class_weights[42-weight-weight0]:newton-choleskyvslbfgsdiffer by 3e-10 on a coefficient of 2e-6 (rtol=1e-4). Two of the fits now stop on L-BFGS-B's "relative reduction of f" (the loss converged to machine precision) instead of on the gradient. On the 4 cases of that test,lbfgsgets closer to the optimum on 2 and further on 2.check_non_transformer_estimators_n_iterforLogisticRegressionCV: on iris, one fit of the regularization path starts from the previous solution, which already meetsgtol(max |gradient| 5.65e-5 vs 5.78e-5), son_iter_ == 0where the check wants >= 1.I also changed
test_zero_max_iter[lbfgs]: L-BFGS-B takes a first step even withmax_iter=0, and that step is now good (score 0.83), so thescore < 0.7check only applies to the other solvers.Not done yet: benchmarks on a many-core machine (the cost of the change of variables is single-threaded), float32 and the array API path (where the change is skipped), and a changelog entry.
AI usage disclosure
I used Claude Code (Claude Opus 5.5) to investigate, prototype, write the code, tests and this description, and run the experiments. I reviewed the code, the results and this text.
🤖 Generated with Claude Code