Skip to content

Should move_to handle non-array API inputs? #34046

Open

Description

@david-cortes-intel

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

Describe the bug and give evidence about its user-facing impact

Internal utility move_to appears to handle cases like Pandas series correctly with most array API namespaces. For example, it works correctly when extracting the namespace and device from libraries like dpnp and array-api-strict and passing those as arguments to move_to, but it doesn't always work with pytorch.

Steps/Code to Reproduce

import os
os.environ["SCIPY_ARRAY_API"] = "1"

import pandas as pd
import torch
from sklearn import set_config
from sklearn.utils._array_api import get_namespace_and_device, move_to

set_config(array_api_dispatch=True)

x = torch.arange(10)
y = pd.Series([1,2,3])

xp, _, device = get_namespace_and_device(x)
y = move_to(y, xp=xp, device=device)

Expected Results

Should work.

Actual Results

Traceback (most recent call last):
  Cell In[3], line 15
    y = move_to(y, xp=xp, device=device)
  File ~/code/scikit-learn/sklearn/utils/_array_api.py:591 in move_to
    array_converted = xp.from_dlpack(array, device=device)
  File ~/miniforge3/envs/dev/lib/python3.14/site-packages/torch/utils/dlpack.py:226 in from_dlpack
    raise AssertionError(
AssertionError: device and copy kwargs not supported when ext_tensor is already a DLPack capsule.

Versions

System:
    python: 3.13.13 | packaged by conda-forge | (main, Apr  8 2026, 02:00:33) [GCC 14.3.0]
executable: /export/users/dcortes/miniforge3/envs/torch19/bin/python
   machine: Linux-6.17.0-20-generic-x86_64-with-glibc2.39

Python dependencies:
      sklearn: 1.9.dev0
          pip: 26.1.1
   setuptools: 70.2.0
        numpy: 2.4.4
        scipy: 1.17.1
       Cython: 3.2.4
       pandas: 3.0.3
   matplotlib: None
       joblib: 1.5.3
threadpoolctl: 3.6.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 64
         prefix: libscipy_openblas
       filepath: /mnt/cached_oses/dcortes/miniforge3/envs/torch19/lib/python3.13/site-packages/numpy.libs/libscipy_openblas64_-32a4b2a6.so
        version: 0.3.31.188.0
threading_layer: pthreads
   architecture: SkylakeX

       user_api: openmp
   internal_api: openmp
    num_threads: 112
         prefix: libgomp
       filepath: /mnt/cached_oses/dcortes/miniforge3/envs/torch19/lib/libgomp.so.1.0.0
        version: None

       user_api: blas
   internal_api: openblas
    num_threads: 64
         prefix: libscipy_openblas
       filepath: /mnt/cached_oses/dcortes/miniforge3/envs/torch19/lib/python3.13/site-packages/scipy.libs/libscipy_openblas-6cdc3b4a.so
        version: 0.3.30
threading_layer: pthreads
   architecture: SkylakeX

Interest in fixing the bug

No.

Activity

  1. david-cortes-intel commented on May 18, 2026

    @david-cortes-intel
    ContributorAuthor

    Possibly the same underlying issue as #33822 - but solution might be different since this doesn't necessarily apply to classifiers.

  2. moved this to Todo in Array APIon May 20, 2026
  3. added
    Needs Investigation
    and removed
    Needs Triage
    on May 20, 2026
  4. ogrisel commented on May 20, 2026

    @ogrisel
    Member

    I confirm I can reproduce. I updated the description to include the full traceback.

    I am not sure if this should be considered a bug or not and if this is the responsibility of move_to or the caller to special case non-array inputs.

    Maybe we could change move_to to handle non-array API inputs, containers that do not implement __array_namespace__, but that expose the NumPy __array__ method ("array-like" object) to call np.asarray first?

    Or alternatively, we could make move_to explicitly fail on non-array API compatible inputs and adapt the caller to handle those data containers explicitly without wrongly assuming that they are array API compatible.

  5. betatim commented on May 20, 2026

    @betatim
    Member

    It feels kind of annoying to not handle pd.Series. You can easily imagine the case where a user loads data with pandas, does some processing of it, then moves to a different namespace and would like to move_to y to that namespace. For example in a scenario like #33737

    What did you expect to happen David, pd.Series -> torch.tensor? My guess is that a pd.Series should become a torch tensor. I think for a series that is "the totally obvious" thing. What about you?

    But if we think about a dataframe it is less obvious to me that turning it into a torch tensor (in this case) is the "totally obvious" thing to do. This is because there are dataframe libs that work well on a CUDA device and dataframes often contain things that can't be well represented in a tensor (categoricals and missing values for examples). So maybe an ideal move_to would pick a dataframe library?? Or because that is hard tell the user that they should do this explicitly. Especially if we ponder a future where we try and dispatch operations to the dataframe library instead of doing it ourselves in the scikit-learn estimator.

    In short, I don't know what it should do. So maybe the thing to do now is to make it an explicit error with instructions for the user on how to fix it. That would fix the immediate problem of "weird error message" and make it clear what the expectation is.

    Then we can think about what behaviour we want and implement this (taking away an exception and allowing additional inputs is much easier to do than to take away something that works later).

  6. ogrisel commented on May 21, 2026

    @ogrisel
    Member

    Note that move_to is currently only exposed by a private import (from the private sklearn.utils._array_api module) so end-users should not be able to use directly.

    I think the public way to trigger this problem was #33822. I would rather wait to fix this particular issue (and related issues) before making a general recommendation on how move_to should behave.

  7. david-cortes-intel commented on May 22, 2026

    @david-cortes-intel
    ContributorAuthor

    It feels kind of annoying to not handle pd.Series. You can easily imagine the case where a user loads data with pandas, does some processing of it, then moves to a different namespace and would like to move_to y to that namespace. For example in a scenario like #33737

    What did you expect to happen David, pd.Series -> torch.tensor? My guess is that a pd.Series should become a torch tensor. I think for a series that is "the totally obvious" thing. What about you?

    But if we think about a dataframe it is less obvious to me that turning it into a torch tensor (in this case) is the "totally obvious" thing to do. This is because there are dataframe libs that work well on a CUDA device and dataframes often contain things that can't be well represented in a tensor (categoricals and missing values for examples). So maybe an ideal move_to would pick a dataframe library?? Or because that is hard tell the user that they should do this explicitly. Especially if we ponder a future where we try and dispatch operations to the dataframe library instead of doing it ourselves in the scikit-learn estimator.

    In short, I don't know what it should do. So maybe the thing to do now is to make it an explicit error with instructions for the user on how to fix it. That would fix the immediate problem of "weird error message" and make it clear what the expectation is.

    Then we can think about what behaviour we want and implement this (taking away an exception and allowing additional inputs is much easier to do than to take away something that works later).

    That's a good question.

    I would definitely expect for a Series object to be casted to a torch tensor in this case.

    For a pd.DataFrame object, I would still expect the same if the move_to function is from scikit-learn and the namespace is torch, as opposed to something else like cudf (which is not supported AFAIK), but I would not expect it to be casted if the namespace is numpy.

    Reasons:

    • Currently, array API is meant to work with a small subset of operations which is geared towards dense and homogeneous numeric arrays. Cases where categorical columns would be used (e.g. decision trees, OHE, etc.) would not be reasonable to support under array API, and this move_to function I presume is mostly meant to serve array API workflows.
    • While some libraries might support other cases like sparse features that pandas also offers, those fall outside of the DLpack protocol (which is embedded in array API) that is meant to be used for inter-library operability. I think it's reasonable for move_to to operate within DLpack limits in these cases, but this probably would need to be documented.
    • I would expect the output from move_to to be intended for usage in scikit-learn objects, which for example do not make a distinction between NULL and NaN, or implicit vs. signaling NaN and similar, so I do not think details like those should matter, plus they aren't part of the array API standard.
    • The analog standard API for dataframes appears to be stalled or dead by this point, so I do not think cases like move_to(pd.DataFrame, xp=cudf) (where a different behavior might be more obvious) are expected to be covered in the future.

    And to add more details, my expectations in other cases would be as follows:

    • Pandas objects: if namespace is numpy, then return as-is, otherwise treat all columns as numeric, error out if conversion is not possible, and return an array from the desired namespace.
    • Polars objects:
      • If they are on CPU, then treat them the same as pandas objects.
      • If they are on GPU and namespace is numpy, then either (a) return the same polars object but with data moved to CPU, or (b) interpret all columns as numeric and return numpy.
      • If they are on GPU and namespace is not numpy, then interpret all columns as numeric and return an array from the desired namespace.
    • Other CPU-based DF objects (e.g. arrow, other libraries if ever supported, etc.): treat the same as pandas.
    • Other GPU-based DF objects (e.g. cuDF): interpret all columns as numeric and return an array from the desired namespace.

    Note that move_to is currently only exposed by a private import (from the private sklearn.utils._array_api module) so end-users should not be able to use directly.

    But the documentation is suggesting users to import things from that private module:
    Image

  8. lucyleeow commented on May 25, 2026

    @lucyleeow
    Member

    Note the same error occurs when a list is passed:

    import torch
    torch.from_dlpack([1,2,3], device="cpu")

    error:

    ---------------------------------------------------------------------------
    AssertionError                            Traceback (most recent call last)
    Cell In[11], line 2
          1 import torch
    ----> 2 torch.from_dlpack([1,2,3], device="cpu")
    
    File ~/miniconda3/envs/skl-array-api/lib/python3.13/site-packages/torch/utils/dlpack.py:226, in from_dlpack(ext_tensor, device, copy)
        224 else:
        225     if device is not None or copy is not None:
    --> 226         raise AssertionError(
        227             "device and copy kwargs not supported when ext_tensor is already a DLPack capsule."
        228         )
        229     # Old versions just call the converter
        230     dlpack = ext_tensor
    
    AssertionError: device and copy kwargs not supported when ext_tensor is already a DLPack capsule.

    This is the cause of the error noted in #33519 and picked up by @StefanieSenger in my PR here: #33778 (review)

    We do need to be able to handle list inputs and it does seem reasonable that move_to is able to handle them. One way could be to except this AssertionError and let the alternative path take over, whereby we convert the list/pandas data structure to numpy array then do xp.asarray.

    (note I double checked the DLPack docs to make sure it does not mention what to do in this case - but of course it only talks about objects that implement __dlpack__ and __dlpack_device__)

  9. lucyleeow commented on May 25, 2026

    @lucyleeow
    Member

    Just for completeness this is the error when you don't use device kwarg:

    torch.from_dlpack([1,2,3])
    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    Cell In[12], line 2
          1 import torch
    ----> 2 torch.from_dlpack([1,2,3])
    
    File ~/miniconda3/envs/skl-array-api/lib/python3.13/site-packages/torch/utils/dlpack.py:231, in from_dlpack(ext_tensor, device, copy)
        229 # Old versions just call the converter
        230 dlpack = ext_tensor
    --> 231 return torch._C._from_dlpack(dlpack)
    
    RuntimeError: from_dlpack received an invalid capsule. Note that DLTensor capsules can be consumed only once, so you might have already constructed a tensor from it once.
  10. added
    Needs Decision
    and removed
    Needs Investigation
    on May 25, 2026
  11. github-actions commented on May 25, 2026

    @github-actions

    Thanks for the work you've done so far. The goal of this comment is to set expectations.

    Deciding on new features or substantial changes is a lengthy process. It frequently happens that no maintainer is available to take on this task right now.

    Please do not create a Pull Request before a decision has been made regarding the proposed work. Making this decision can often take a significant amount of time and effort.

  12. david-cortes-intel commented on May 25, 2026

    @david-cortes-intel
    ContributorAuthor

    I think torch.from_dlpack(list) should be expected to error out, since a Python list is not a memory-contiguous array.

    Per the docs:
    https://data-apis.org/array-api/latest/design_topics/data_interchange.html#non-supported-use-cases

    Use of DLPack requires that the data can be represented by a strided, in-memory layout on a single device.

    Such operation would also error out with array_api_strict:

    import array_api_strict
    array_api_strict.from_dlpack([1,2,3])
    AttributeError: 'list' object has no attribute '__dlpack__'
    

    Thus, move_to should instead avoid passing objects like those (with no DLpack capsule / .__dlpack__) to from_dlpack.

  13. lucyleeow commented on May 26, 2026

    @lucyleeow
    Member

    Good point about memory in Python lists. And from a user perspective, I can definitely see that it makes sense for move_to to work for pandas dataframe but error for a list.

    But move_to is also used extensively internally (and was what it was originally designed for). Now that we allow mixed array input types (everything follows X for estimators, and everything follows y_pred for metrics), we probably should handle e.g., y_pred being an array and y_true being a list.

    Currently, the general pattern is that we use move_to at the start of the function/method. If move_to does not handle lists, we would have to add extra code to handle list to a lot of places. We also could run check_array first before move_to as suggested by @StefanieSenger in #33778 but there are some small problems with this:

    • check_array and move_to both may perform dtype conversions - we may not know the required dtype for check_array if it is performed first or we may end up doing a redundant dtype conversion
    • we may end up performing an redundant conversion, e.g., check_array run on a list would result in numpy array, but required output may be e.g., torch. We could have directly going list -> torch array without the numpy intermediary

    Edit: it's interesting to note that check_array also handles pandas/narwhals dataframe inputs but xp is numpy in this case.


    Also, to clarify - since you are quoting DLPack docs, are you saying that if a data structure is memory-contiguous, you would expect it to be supported by dlpack? Or are you saying, if the data structure is memory-contiguous, it should be supported by move_to?

    Use of DLPack requires that the data can be represented by a strided, in-memory layout on a single device.

    I read that quote as "data can be represented by a strided, in-memory layout on a single device", as in is "able to be", not that it currently is. And a list of numbers can be represented this way?

    Additionally, one column in a dataframe seems to be contiguous, but will all columns in a dataframe be all stored together contiguously? Should memory representation affect how it should be treated by move_to ?

    Regardless, maybe list handling is better discussed in a separate issue? Happy to open one if we decide it is better.

  14. david-cortes-intel commented on May 26, 2026

    @david-cortes-intel
    ContributorAuthor

    @lucyleeow What I'm saying is that xp.from_dlpack is expected to operate on DLpack capsules (attribute __dlpack__). So instead, move_to should ensure that it doesn't pass non-dlpack objects to xp.from_dlpack, even if they are supported as input to move_to. For example, it could convert them to numpy first in cases of built-in lists and tuples.

  15. betatim commented on Jun 1, 2026

    @betatim
    Member

    One thing to keep in mind is that we want existing code to continue working in a world where array API support is turned on by default. This means that move_to needs to be able to handle all the array-like inputs that users can pass. I think this means that we can't make it error when you pass a list to it. In the comments following #33444 (comment) we discuss the "existing array-like inputs should continue to work" point and what that means (looking at you pytorch CPU tensors)


    Note that move_to is currently only exposed by a private import (from the private sklearn.utils._array_api module) so end-users should not be able to use directly.

    But the documentation is suggesting users to import things from that private module:

    The docs in the screenshot are about move_estimator_to. This is in a private namespace and we tell users to use it. It will be in a public namespace when array API support is turned on by default. Until then it is in a private namespace to signal its experimental nature/lack of API stability guarantees. More details and discussion of this in #34135 (comment)

  16. changed the title [-]`move_to` not always working with torch namespace[/-] [+]Should `move_to` handle non-array API inputs?[/+] on Jun 2, 2026
  17. lucyleeow commented on Jun 2, 2026

    @lucyleeow
    Member

    I've amended the title, because I think this issue can tackle the more general question of how non-array API inputs (pandas, list) should be handled by move_to. Please feel free to edit if anyone disagrees though.

  18. lucyleeow commented on Jun 26, 2026

    @lucyleeow
    Member

    I've realised that we can just pass non-array inputs (list, pandas) through move_to unchanged, then let check_array handle them. For internal use, this makes sense as we routinely use check_array on inputs and it means the complicated logic of dealing with pandas/df inputs (inferring dtype alone is many lines of code) is only ever handled by check_array.

    It does not answer the original question as to whether the 'public' move_toand move_estimator_toshould handle non-array inputs though. One possibility is that we could have a private _move_to that only handles array inputs and a public move_to that uses the private _move_to and check_array...?

    WDYT @betatim @ogrisel ?

  19. betatim commented on Jul 7, 2026

    @betatim
    Member

    I like the idea of passing things like list straight through move_to. Do we need to make it public? I think move_estimator_to is the only thing we have to make public in order for users to be able to move estimators from one namespace/device to another.

    If move_to is private I think it is fine for it to be a little "weird" in the sense that move_to([1, 2, 3], xp=torch, device="cuda") returns the list unchanged/unmoved.

  20. lucyleeow commented on Jul 8, 2026

    @lucyleeow
    Member

    It means we don't have to have a long discussion about what types of dataframes are accepted and it maintains consistency with what is already happening (in check_array)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions