Repository navigation
FEA Add array API support for PoissonRegressor with LBFGS - #33348
Conversation
7e05c24 to
a9c11a2
Compare
a9c11a2 to
289fa29
Compare
289fa29 to
f68d464
Compare
|
I think the refactoring done in this PR seems good. What do you think @ogrisel ? |
|
@lorentzenchr Would it be fine with you if I fix this PR or would you prefer to do it yourself? |
Go ahead. |
|
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. |
OmarManzoor
left a comment
There was a problem hiding this comment.
LGTM. @ogrisel please merge when you are satisfied.
|
|
||
| def __sklearn_tags__(self): | ||
| tags = super().__sklearn_tags__() | ||
| tags.array_api_support = self.solver == "lbfgs" |
There was a problem hiding this comment.
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:
| 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?)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.There was a problem hiding this comment.
+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.
There was a problem hiding this comment.
Okay I tried to address this appropriately. @betatim can you have a look now?
There was a problem hiding this comment.
I actually added another test for the warm start case.
There was a problem hiding this comment.
Thanks for the fix! Looks good to me. I will make a new PR to fix LogisticRegression as well (thanks for finding it Olivier)
|
@OmarManzoor Shall I merge? |
I think it can be merged but what do you think should we let @betatim have another look? |
Ok |
|
@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? |
|
Even if someone can reproduce, we only promised fitting with array API. Scoring is an additional step. |
|
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.9759193658828735If it still fails for you on |
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)