Skip to content

Automatically move y (and sample_weight) to the same device and namespace as X  #28668

Closed

Description

@betatim

(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.

Activity

  1. added
    Needs Triage
    on Mar 20, 2024
  2. betatim commented on Mar 20, 2024

    @betatim
    MemberAuthor

    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 y to "follow" X when needed is a good solution and somehow sensible.

    So right now I'm +1

  3. removed
    Needs Triage
    on Mar 20, 2024
  4. changed the title [-]Automatically move `y` to same device and namespace as `X` [/-] [+]Automatically move `y` to the same device and namespace as `X` [/+] on Mar 20, 2024
  5. ogrisel commented on Mar 20, 2024

    @ogrisel
    Member

    +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.

  6. ogrisel commented on Mar 20, 2024

    @ogrisel
    Member

    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 in ensure_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:

    >>> import array_api_strict as xp_strict
    >>> import array_api_compat.torch as xp_torch
    >>> reference = xp_strict.ones(3)
    >>> reference.device
    CPU_DEVICE
    >>> xp_strict.asarray(xp_torch.ones(3, device="mps"), device=reference.device)
    Traceback (most recent call last):
      Cell In[49], line 1
        xp_strict.asarray(xp_torch.ones(3, device="mps"), device=reference.device)
      File ~/miniforge3/envs/dev/lib/python3.11/site-packages/array_api_strict/_creation_functions.py:91 in asarray
        res = np.array(obj, dtype=_np_dtype, copy=copy)
      File ~/miniforge3/envs/dev/lib/python3.11/site-packages/torch/_tensor.py:1030 in __array__
        return self.numpy()
    TypeError: can't convert mps:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

    In this case, we should instead use the new improvements made to the dlpack and Array API specs:

    Starting Python array API standard v2023, a copy can be explicitly requested (or disabled) through the new copy argument of from_dlpack(). When a copy is made, the producer must set the DLPACK_FLAG_BITMASK_IS_COPIED bit flag. It is also possible to request cross-device copies through the new device argument, though the v2023 standard only mandates the support of kDLCPU.

    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_numpy hack before calling back to xp.asarray if 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 y and sample_weight are numpy or other non-namespace containers.

  7. lorentzenchr commented on Mar 25, 2024

    @lorentzenchr
    Member

    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.)

  8. moved this to Discussion in Array APIon May 17, 2024
  9. ogrisel commented on Jun 7, 2024

    @ogrisel
    Member

    +1 for documenting the default device move semantics in the _array_api.rst file. Personally, I don't think that a warning is necessary and could be counter productive for typical pipelines. In particular, consider the following pipeline:

    pipeline = make_pipeline(
       SomeDataFrameAwareFeatureExtractor(),
       MoveFeaturesToPyTorch(device="cuda"),
       SomeArrayAPICapableClassifier(),
    )
    pipeline.fit(df_train[feature_columns], df_train[target_column])
    pipeline.predict(df_test[feature_columns])

    If df[target_column] has string-valued or categorical valued class labels, the user would have no way to convert y to 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_weight and other array-based metadata will probably want to follow a similar policy for consistency.

  10. lucyleeow commented on Mar 14, 2025

    @lucyleeow
    Member

    Just wanted to add a reference #29431 (comment) , not sure if we have made a decision on whether sample_weight should follow X too.

  11. betatim commented on Mar 17, 2025

    @betatim
    MemberAuthor

    I think sample_weight should follow X as well.

    I think sample_weight and y are all small compared to X, so they will be faster to move. And the user can move X via a transformer, but not any of the other things. Maybe we should call this "everything follows X" but that isn't quite as catchy as "y follows X" :-/ (for some definition of "catchy")

  12. ogrisel commented on Mar 28, 2025

    @ogrisel
    Member

    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.

  13. lucyleeow commented on Apr 8, 2025

    @lucyleeow
    Member

    Just wanted to summarise (including what was discussed last meeting):

    • y and sample_weight following X - 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).
    • hyperparameters that are arrays following X - this is more debatable but I think consensus was that this would be nice as well

    How this is move done (ref: #28668 (comment)):

    • numpy arrays and Python lists are easy to move to the same namespace/device
    • arrays that are on a different namespace/device combo:
      • try ~array_api.from_dlpack (@ogrisel you mention that "there is no guarantee that cross-device transfers work in general" - the DLPack docs say that from_dlpack will 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?)
      • if above does not work, fallback on internal _convert_to_numpy to convert to numpy and then xp.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 on array-api-compat/array-api-strict`, I am currently getting a different error when running e.g.:

    >>> import array_api_compat.torch as xp_torch
    >>> import array_api_compat.numpy as xp_np
    >>> xp_np.from_dlpack(xp_torch.ones(3, device="mps"))

    Error:

    NotImplementedError: Could not run 'aten::empty.memory_format' with arguments from the 'MPS' backend. This could be because the operator doesn't exist for this backend, or was omitted during the selective/custom build process (if using custom build). If you are a Facebook employee using PyTorch on mobile, please visit https://fburl.com/ptmfixes for possible resolutions. 'aten::empty.memory_format' is only available for these backends: [CPU, Meta, QuantizedCPU, QuantizedMeta, MkldnnCPU, SparseCPU, SparseMeta, SparseCsrCPU, SparseCsrMeta, BackendSelect, Python, FuncTorchDynamicLayerBackMode, Functionalize, Named, Conjugate, Negative, ZeroTensor, ADInplaceOrView, AutogradOther, AutogradCPU, AutogradCUDA, AutogradHIP, AutogradXLA, AutogradMPS, AutogradIPU, AutogradXPU, AutogradHPU, AutogradVE, AutogradLazy, AutogradMTIA, AutogradPrivateUse1, AutogradPrivateUse2, AutogradPrivateUse3, AutogradMeta, AutogradNestedTensor, Tracer, AutocastCPU, AutocastXPU, AutocastMPS, AutocastCUDA, FuncTorchBatched, BatchedNestedTensor, FuncTorchVmapMode, Batched, VmapMode, FuncTorchGradWrapper, PythonTLSSnapshot, FuncTorchDynamicLayerFrontMode, PreDispatch, PythonDispatcher].

    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_true should follow y_pred (ref: #30439 (comment)) - should we create a new issue for this?

  14. 27 remaining items

  15. Fazel94 commented on Jul 14, 2026

    @Fazel94
    Contributor

    I am working on LinearDiscriminantAnalysis

  16. aminehd commented on Jul 14, 2026

    @aminehd
    Contributor

    I'd like to take PoissonRegressor.

  17. aminehd commented on Jul 15, 2026

    @aminehd
    Contributor

    Created pr for this
    dd3b48c
    Really appreciate a review

  18. ogrisel commented on Aug 18, 2026

    @ogrisel
    Member

    I think we can close this meta-issue once #34771 is merged.

  19. ogrisel commented on Aug 25, 2026

    @ogrisel
    Member

    I double checked and the only XFAIL marker for check_array_api_mixed_inputs is for GaussianNB that requires an upstream fix for pytorch/pytorch#188128.

  20. moved this from In progress to Done in Labson Aug 25, 2026
  21. moved this from Done to In Progress in Array APIon Aug 25, 2026
  22. moved this from In Progress to Done in Array APIon Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions