Skip to content

FEA Add array API support for PoissonRegressor with LBFGS - #33348

Merged
betatim merged 20 commits into
scikit-learn:mainfrom
lorentzenchr:poisson_array_api
Mar 17, 2026
Merged

betatim merged 20 commits into
scikit-learn:mainfrom
lorentzenchr:poisson_array_api

Conversation

@lorentzenchr

@lorentzenchr lorentzenchr commented Feb 21, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Similar to #32644.

What does this implement/fix? Explain your changes.

This adds array API support to PoissonRegressor(solver="lbfgs").

AI usage disclosure

None

Any other comments?

Depends on #33345.(merged)

@OmarManzoor

Copy link
Copy Markdown
Contributor

I think the refactoring done in this PR seems good. What do you think @ogrisel ?

@OmarManzoor

Copy link
Copy Markdown
Contributor

@lorentzenchr Would it be fine with you if I fix this PR or would you prefer to do it yourself?

@lorentzenchr

Copy link
Copy Markdown
Member Author

@lorentzenchr Would it be fine with you if I fix this PR or would you prefer to do it yourself?

Go ahead.

@adrinjalali adrinjalali added this to Labs Mar 9, 2026
@adrinjalali adrinjalali moved this to Todo in Labs Mar 9, 2026
Comment thread sklearn/_loss/tests/test_loss.py Resolved
@lorentzenchr

Copy link
Copy Markdown
Member Author

FYI, we have more control over the other solvers, in particular newton-cg and newton-cholesky, see also #16635 (comment). Maybe, they give better speedups for Poisson GLMs.
For the time being, this PR is consequential, so I am still +1.

@OmarManzoor OmarManzoor left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. @ogrisel please merge when you are satisfied.

Comment thread sklearn/linear_model/_glm/glm.py Resolved
Comment thread sklearn/linear_model/_glm/glm.py Resolved

def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.array_api_support = self.solver == "lbfgs"

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.

If you set warm_start=True we hit code that uses np instead of xp (np.concat on L259)

I started down the road of converting it to use xp thinking that it can't be that hard. But then I realised that coef has to be a numpy array. At which point I stopped, this is probably going to be more than a two line code suggestion.


If we don't make warm_start work should we rewrite this condition like this:

Suggested change
tags.array_api_support = self.solver == "lbfgs"
tags.array_api_support = self.solver == "lbfgs" and self.warm_start == False

Though in both cases calling fit(X_xp, y_xp) leads to a generic/not specific error message ("TypeError: can't convert mps:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first." because I am using torch).

I am not sure if we have a precedent for how to handle getting a specific error message ("Enable array API support!"). Should we make a new issue to discuss this topic and then come back to it? (Also fine to address it directly in this PR but might be a rabbit hole?)

@OmarManzoor OmarManzoor Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

So I added a parametrization with warm_start and the tests seem to pass. It might have been that setting device=None in the initialization of HalfPoissonLossArrayAPI was causing issues.

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.

I think the test passes because it does not call fit twice. The following two snippets together is what produces the error for me. This fits the model once:

In [1]: import numpy as np
   ...: from sklearn import config_context
   ...: from sklearn.linear_model import PoissonRegressor
   ...:
   ...: rng = np.random.default_rng(42)
   ...: X = rng.standard_normal((200, 5))
   ...: y = np.abs(rng.standard_normal(200)) + 0.1
   ...:
   ...: # Fit with array-api-strict
   ...: import torch as xp_strict
   ...: X_xp = xp_strict.asarray(X, device="mps", dtype=xp_strict.float32)
   ...: y_xp = xp_strict.asarray(y, device="mps", dtype=xp_strict.float32)
   ...:
   ...: with config_context(array_api_dispatch=True):
   ...:     reg_xp = PoissonRegressor(alpha=1.0, solver="lbfgs", max_iter=300, warm_start=True).fit(X_xp, y_xp)
   ...:     pred_xp = reg_xp.predict(X_xp)
   ...:     score_xp = reg_xp.score(X_xp, y_xp)

and then fitting again:

In [5]: with config_context(array_api_dispatch=True):
   ...:     reg_xp.fit(X_xp, y_xp)
   ...:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[5], line 2
      1 with config_context(array_api_dispatch=True):
----> 2     reg_xp.fit(X_xp, y_xp)

File ~/git/scikit-learn/sklearn/base.py:1385, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs)
   1378     estimator._validate_params()
   1380 with config_context(
   1381     skip_parameter_validation=(
   1382         prefer_skip_nested_validation or global_skip_validation
   1383     )
   1384 ):
-> 1385     return fit_method(estimator, *args, **kwargs)

File ~/git/scikit-learn/sklearn/linear_model/_glm/glm.py:259, in _GeneralizedLinearRegressor.fit(self, X, y, sample_weight)
    256 if self.warm_start and hasattr(self, "coef_"):
    257     if self.fit_intercept:
    258         # LinearModelLoss needs intercept at the end of coefficient array.
--> 259         coef = np.concatenate((self.coef_, np.array([self.intercept_])))
    260     else:
    261         coef = self.coef_

File ~/miniconda/envs/sklearn-py3.13/lib/python3.13/site-packages/torch/_tensor.py:1225, in Tensor.__array__(self, dtype)
   1223     return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype)
   1224 if dtype is None:
-> 1225     return self.numpy()
   1226 else:
   1227     return self.numpy().astype(dtype, copy=False)

TypeError: can't convert mps:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

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.

+1 for applying @betatim's suggestion https://github.com/scikit-learn/scikit-learn/pull/33348/changes#r2930336180 and opening a follow-up issue.

It seems we already have a similar problem for LogisticRegression:

# %%
import os
import torch
import sklearn
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression


os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
os.environ["SCIPY_ARRAY_API"] = "1"
sklearn.set_config(array_api_dispatch=True)

X, y = make_classification(n_samples=1000, n_features=10, random_state=42)
X = torch.from_numpy(X).float().to("mps")
y = torch.from_numpy(y).float().to("mps")
# %%
clf = LogisticRegression(warm_start=True)
clf.__sklearn_tags__().array_api_support

# %%
clf.fit(X, y)
clf.fit(X, y)

The array API support tag is set to True but then the second fit call fails with TypeError: can't convert mps:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first. as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Okay I tried to address this appropriately. @betatim can you have a look now?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I actually added another test for the warm start case.

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.

Thanks for the fix! Looks good to me. I will make a new PR to fix LogisticRegression as well (thanks for finding it Olivier)

@lorentzenchr

Copy link
Copy Markdown
Member Author

@OmarManzoor Shall I merge?

@OmarManzoor

Copy link
Copy Markdown
Contributor

@OmarManzoor Shall I merge?

I think it can be merged but what do you think should we let @betatim have another look?

@lorentzenchr

Copy link
Copy Markdown
Member Author

I think it can be merged but what do you think should we let @betatim have another look?

Ok

@betatim
betatim merged commit a8c13a2 into scikit-learn:main Mar 17, 2026
38 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in Labs Mar 17, 2026
@ogrisel
ogrisel deleted the poisson_array_api branch March 17, 2026 13:53
@ogrisel

ogrisel commented Mar 17, 2026

Copy link
Copy Markdown
Member

@OmarManzoor: it seems that we forgot to address that bug with the score method before merging:

#33348 (comment)

@OmarManzoor

Copy link
Copy Markdown
Contributor

@OmarManzoor: it seems that we forgot to address that bug with the score method before merging

I was not able to reproduce that error. Are you still getting it?

@lorentzenchr

Copy link
Copy Markdown
Member Author

Even if someone can reproduce, we only promised fitting with array API. Scoring is an additional step.

@betatim

betatim commented Mar 18, 2026

Copy link
Copy Markdown
Member

When I run the snippet in the details section of the comment you linked Olivier I don't get an error:

In [5]: model = PoissonRegressor()
   ...: model.fit(X_mps, y_mps).n_iter_
Out[5]: 6

In [6]: model.score(X_mps, y_mps)
Out[6]: 0.9759193658828735

If it still fails for you on main we should make an issue to track this

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

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

4 participants