Repository navigation
Open
Labels
Description
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: SkylakeXInterest in fixing the bug
No.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsTodo
Activity
david-cortes-intel commentedon May 18, 2026
Possibly the same underlying issue as #33822 - but solution might be different since this doesn't necessarily apply to classifiers.
ogrisel commentedon May 20, 2026
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_toor the caller to special case non-array inputs.Maybe we could change
move_toto handle non-array API inputs, containers that do not implement__array_namespace__, but that expose the NumPy__array__method ("array-like" object) to callnp.asarrayfirst?Or alternatively, we could make
move_toexplicitly 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.betatim commentedon May 20, 2026
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 tomove_toyto that namespace. For example in a scenario like #33737What did you expect to happen David,
pd.Series->torch.tensor? My guess is that apd.Seriesshould 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_towould 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).
ogrisel commentedon May 21, 2026
Note that
move_tois currently only exposed by a private import (from the privatesklearn.utils._array_apimodule) 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_toshould behave.david-cortes-intel commentedon May 22, 2026
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.DataFrameobject, I would still expect the same if themove_tofunction is from scikit-learn and the namespace istorch, as opposed to something else likecudf(which is not supported AFAIK), but I would not expect it to be casted if the namespace isnumpy.Reasons:
move_tofunction I presume is mostly meant to serve array API workflows.move_toto operate within DLpack limits in these cases, but this probably would need to be documented.move_toto be intended for usage in scikit-learn objects, which for example do not make a distinction betweenNULLandNaN, or implicit vs. signalingNaNand similar, so I do not think details like those should matter, plus they aren't part of the array API standard.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:
But the documentation is suggesting users to import things from that private module:

lucyleeow commentedon May 25, 2026
Note the same error occurs when a list is passed:
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_tois able to handle them. One way could be to except thisAssertionErrorand let the alternative path take over, whereby we convert the list/pandas data structure to numpy array then doxp.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__)lucyleeow commentedon May 25, 2026
Just for completeness this is the error when you don't use
devicekwarg:--------------------------------------------------------------------------- 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.github-actions commentedon May 25, 2026
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.
david-cortes-intel commentedon May 25, 2026
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
Such operation would also error out with
array_api_strict:Thus,
move_toshould instead avoid passing objects like those (with no DLpack capsule /.__dlpack__) tofrom_dlpack.lucyleeow commentedon May 26, 2026
Good point about memory in Python lists. And from a user perspective, I can definitely see that it makes sense for
move_toto work for pandas dataframe but error for a list.But
move_tois also used extensively internally (and was what it was originally designed for). Now that we allow mixed array input types (everything followsXfor estimators, and everything followsy_predfor metrics), we probably should handle e.g.,y_predbeing an array andy_truebeing a list.Currently, the general pattern is that we use
move_toat the start of the function/method. Ifmove_todoes not handle lists, we would have to add extra code to handle list to a lot of places. We also could runcheck_arrayfirst beforemove_toas suggested by @StefanieSenger in #33778 but there are some small problems with this:check_arrayandmove_toboth may perform dtype conversions - we may not know the required dtype forcheck_arrayif it is performed first or we may end up doing a redundant dtype conversioncheck_arrayrun 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 intermediaryEdit: it's interesting to note that
check_arrayalso handles pandas/narwhals dataframe inputs butxpis 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?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.
david-cortes-intel commentedon May 26, 2026
@lucyleeow What I'm saying is that
xp.from_dlpackis expected to operate on DLpack capsules (attribute__dlpack__). So instead,move_toshould ensure that it doesn't pass non-dlpack objects toxp.from_dlpack, even if they are supported as input tomove_to. For example, it could convert them to numpy first in cases of built-in lists and tuples.betatim commentedon Jun 1, 2026
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_toneeds 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 alistto 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)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)[-]`move_to` not always working with torch namespace[/-][+]Should `move_to` handle non-array API inputs?[/+]lucyleeow commentedon Jun 2, 2026
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.lucyleeow commentedon Jun 26, 2026
I've realised that we can just pass non-array inputs (list, pandas) through
move_tounchanged, then letcheck_arrayhandle them. For internal use, this makes sense as we routinely usecheck_arrayon 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 bycheck_array.It does not answer the original question as to whether the 'public'
move_toandmove_estimator_toshould handle non-array inputs though. One possibility is that we could have a private_move_tothat only handles array inputs and a publicmove_tothat uses the private_move_toandcheck_array...?WDYT @betatim @ogrisel ?
betatim commentedon Jul 7, 2026
I like the idea of passing things like
liststraight throughmove_to. Do we need to make it public? I thinkmove_estimator_tois 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_tois private I think it is fine for it to be a little "weird" in the sense thatmove_to([1, 2, 3], xp=torch, device="cuda")returns the list unchanged/unmoved.lucyleeow commentedon Jul 8, 2026
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)