Repository navigation
Description
(From #27800 (comment) by @ogrisel)
The proposal/idea is to allow y to not be on the same device (and namespace?) as X when using Array API inputs. Currently we require/assume that they are on the same device and namespace, it is a requirement. However pipelines can't modify y which means it is not possible to move from CPU to GPU as one of the steps of the pipeline, the whole pipeline has to stay on one device. The below details some example and code to motivate allowing X ad y being on different devices (and namespaces).
Suppose we have:
>>> import torch
>>> from sklearn import set_config
>>> from sklearn.datasets import make_regression
>>> from sklearn.linear_model import Ridge
>>> set_config(array_api_dispatch=True)
>>> X, y = make_regression(n_samples=int(1e5), n_features=int(1e3), random_state=0)
>>> X_torch_cuda = torch.tensor(X).to("cuda")
>>> y_torch_cuda = torch.tensor(y).to("cuda")I did a quick benchmark with timeit on a host with a 32 cores CPU and an A100 GPU: we get a bit more than 10x speed-up (which is in the range of what I would have expected):
>>> %time Ridge(solver="svd").fit(X, y)
CPU times: user 1min 29s, sys: 1min 4s, total: 2min 34s
Wall time: 6.18 s
Ridge(solver='svd')
>>> %time Ridge(solver="svd").fit(X_torch_cuda, y_torch_cuda)
CPU times: user 398 ms, sys: 2.74 ms, total: 401 ms
Wall time: 402 ms
Ridge(solver='svd')I also tried the following:
>>> Ridge(solver="svd").fit(X_torch_cuda, y)
Traceback (most recent call last):
Cell In[36], line 1
Ridge(solver="svd").fit(X_torch_cuda, y)
File ~/code/scikit-learn/sklearn/base.py:1194 in wrapper
return fit_method(estimator, *args, **kwargs)
File ~/code/scikit-learn/sklearn/linear_model/_ridge.py:1197 in fit
device_ = device(*input_arrays)
File ~/code/scikit-learn/sklearn/utils/_array_api.py:104 in device
raise ValueError("Input arrays use different devices.")
ValueError: Input arrays use different devices.I think it might be reasonable to expect this pattern to fail in general. explicitly ask the the user to provide inputs with consistently allocated data buffers.
However, we might want to be more lenient for the particular case of y (and sample_weight) and change Ridge.fit to automatically move y to the same namespace and device as X:
y = xp.asarray(y, device=device(X))The reason would be to improve the usability of the Array API for the following pipelines:
X_pandas_df, y_pandas_series = fetch_some_pandas_data()
pipeline = make_pipeline(
some_column_transformer(), # works on CPU on the input dataframe
FunctionTransformer(func=lambda X: torch.tensor(X).to("float32").to("cuda")),
Ridge(solver="svd"),
)
pipeline.fit(X_pandas_df, y_pandas_series)The pipeline steps can only transform X and not y (or sample_weight). So it means that user would have to instead call:
pipeline.fit(X_pandas_df, torch.tensor(y_pandas_series).to("cuda"))which feels a bit weird/cumbersome to me.
This might not be a big deal though and I don't want to delay this PR to get a consensus on this particular point: I think it's fine the way it is for now but we might want come back to the UX of pipelines with Array API steps later. I will open a dedicated issue.
If we take action there are a few estimators that need double checking. For example LinearDiscriminantAnalysis currently raises low level PyTorch exceptions when X and y are on different devices.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
betatim commentedon Mar 20, 2024
After thinking about this for a bit I think I like the idea. It solves a problem for which we haven't found a good solution in a while now (how to move from one device to another). I think allowing
yto "follow"Xwhen needed is a good solution and somehow sensible.So right now I'm +1
[-]Automatically move `y` to same device and namespace as `X` [/-][+]Automatically move `y` to the same device and namespace as `X` [/+]ogrisel commentedon Mar 20, 2024
+1 in general, and even more so to make it possible to train classifier pipelines on a GPU with str object-typed class labels passed to the pipeline as we usually allow.
ogrisel commentedon Mar 20, 2024
Note, on the implementation side, to move NumPy arrays and Python lists to a specific array namespace/device combo,
xp.asarray(source, device=device)should work (as we currently do inensure_commone_namespace_device).But if the things to move are already already on another namespace/device combo, that will most likely fail in general, for instance with torch:
In this case, we should instead use the new improvements made to the dlpack and Array API specs:
https://github.com/dmlc/dlpack/blob/main/docs/source/python_spec.rst
But note that there is no guarantee that cross-device transfers work in general, so we might always have to move through a CPU device if needed.
Furthermore, this is not yet implemented in
array-api-compat/array-api-strict:data-apis/array-api-compat#86 (comment)
In the mean time we will have to rely on our
_convert_to_numpyhack before calling back toxp.asarrayif we need to do cross-non-numpy-namespaces transfers.For now we can decide to implement the "auto-follow" thing only when X is a namespace and
yandsample_weightare numpy or other non-namespace containers.lorentzenchr commentedon Mar 25, 2024
A priori, I‘m +1 for only allowing X and y on the same device.
I‘m also +1 to allow y on a different device and scikit-learn moving it to the device of X. But only if it is clearly documented. We could even think to start with a warning (that we can remove later.)
ogrisel commentedon Jun 7, 2024
+1 for documenting the default device move semantics in the
_array_api.rstfile. Personally, I don't think that a warning is necessary and could be counter productive for typical pipelines. In particular, consider the following pipeline:If
df[target_column]has string-valued or categorical valued class labels, the user would have no way to convertyto a pytorch tensor on the same cuda device. The only option would be manually label encode the target into integers and move the result to pytorch/cuda. And then, after calling predict, do the inverse operation manually again. This would significantly degrade the user experience when working with non-integer class labels.Note that
sample_weightand other array-based metadata will probably want to follow a similar policy for consistency.lucyleeow commentedon Mar 14, 2025
Just wanted to add a reference #29431 (comment) , not sure if we have made a decision on whether
sample_weightshould followXtoo.betatim commentedon Mar 17, 2025
I think
sample_weightshould followXas well.I think
sample_weightandyare all small compared toX, so they will be faster to move. And the user can moveXvia a transformer, but not any of the other things. Maybe we should call this "everything followsX" but that isn't quite as catchy as "yfollowsX" :-/ (for some definition of "catchy")ogrisel commentedon Mar 28, 2025
Since we seem to have a consensus, let's move forward. @lucyleeow please feel free to open a PR to update the array API doc accordingly.
lucyleeow commentedon Apr 8, 2025
Just wanted to summarise (including what was discussed last meeting):
yandsample_weightfollowingX- required; it's otherwise not possible to implement pipelines where the namespace of X changes across steps (for instance via a FunctionTransformer that moves extracted numerical features to pytorch on GPU after a first few steps that work on pandas inputs on GPU).X- this is more debatable but I think consensus was that this would be nice as wellHow this is move done (ref: #28668 (comment)):
~array_api.from_dlpack(@ogrisel you mention that "there is no guarantee that cross-device transfers work in general" - the DLPack docs say thatfrom_dlpackwill accept "any (array) object with the two DLPack methods (dlpack() and dlpack_device()) implemented" - is that what you meant, or even if the 2 methods are implemented, there is still no guarantee of successful transfer?)_convert_to_numpyto convert to numpy and thenxp.asarray: i.e. do a namespace_origin -> numpy -> namespace_destination conversion.compat/strict `from_dlpack` error
With reference to your comment on
from_dlpack not yet being implemented onarray-api-compat/array-api-strict`, I am currently getting a different error when running e.g.:Error:
Interesting that it specifically mentions Facebook employees..?
I think this is slightly out of scope for this issue but we also have the issue of whether
y_trueshould followy_pred(ref: #30439 (comment)) - should we create a new issue for this?27 remaining items
Fazel94 commentedon Jul 14, 2026
I am working on
LinearDiscriminantAnalysisaminehd commentedon Jul 14, 2026
I'd like to take PoissonRegressor.
FIX PoissonRegressor mixed namespace/device array API inputs
aminehd commentedon Jul 15, 2026
Created pr for this
dd3b48c
Really appreciate a review
FIX PoissonRegressor mixed namespace/device array API inputs
FIX PoissonRegressor mixed namespace/device array API inputs
FIX PoissonRegressor mixed namespace/device array API inputs
ogrisel commentedon Aug 18, 2026
I think we can close this meta-issue once #34771 is merged.
ogrisel commentedon Aug 25, 2026
I double checked and the only XFAIL marker for
check_array_api_mixed_inputsis forGaussianNBthat requires an upstream fix for pytorch/pytorch#188128.