Skip to content

Add MoveTo transformer to move X to a different array namespace/device #33737

Open

Description

@betatim

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.

This issue describes a new transformer MoveTo that can be used to move X to another array namespace and device. The goal of the transformer is to move the input array X to a specified array namespace (numpy, torch, cupy) and device (CPU, CUDA, MPS, etc). The transformer can not move y or sample_weight but that is Ok, because of #28668.

The goal is to enable a Pipeline like the following when using the experimental support for array API (and other use-cases where processing has to move from one namespace/device to another):

df = pd.read_parquet("data_file.parquet")
X = df[categorical_feature_names]  # categorical or str/object dtype
y = df[target_column_name]  # continuous value to regress.

pipeline = make_pipeline(
   TargetEncoder(),  # works on categorical X but also needs y, hence CPU for both
   MoveTo(namespace=torch, device="cuda:0"),
   Ridge(),  # only numerical inputs: faster to do it all on GPU, y follows X => y_pred on GPU.
)

cv_results = cross_validate(pipeline, X, y, scoring="r2")

Currently you can make the example above work by replacing MoveTo with FunctionTransformer(partial(torch.asarray, device="cuda:0")). However it is difficult for the average user to discover this particular FunctionTransformer incantation and looking towards the future where we want to offer a function that can "translate" a whole pipeline from running on one namespace/device to another (e.g. train on GPU, then deploy on CPU) having an explicitly named step that can be specially treated is useful.

xref #33444

Activity

  1. github-actions commented on Apr 13, 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.

  2. moved this to Todo in Array APIon Apr 13, 2026
  3. moved this from Todo to Discussion in Array APIon Apr 13, 2026
  4. ogrisel commented on Apr 13, 2026

    @ogrisel
    Member

    I think it's good to have an explicit transformer for this.

    Another reason would be to make it possible for move_estimator_to to change the target namespace and device of this step by implementing a special __sklearn_array_api_convert__ method for that particular class.

    This would be particularly useful to train a pipeline on a GPU host with PyTorch or CuPy, pickle it, and load it on a CPU-only host with a lighter set of dependencies to compute predictions there.

  5. added
    Needs Decision
    and removed
    Needs Decision
    on Apr 13, 2026
  6. github-actions commented on Apr 13, 2026

    @github-actions
  7. betatim commented on Apr 14, 2026

    @betatim
    MemberAuthor

    One more question: where in the library should we add this transformer? And how should we handle marking it as experimental?

    There is precedent for using sklearn.experimental to make estimators appear in their final location, but it feels a bit weird to have skelarn.set_config() and then also having to import from sklearn.experimental.

    What do you think about doing what sklearn.experimental does but when people set_config(array_api_dispatch=True)? That seems like a nice solution, only caveat is investigating if we can easily "hide" the transformer again when set_config(array_api_dispatch=False) is called.

  8. lorentzenchr commented on Apr 16, 2026

    @lorentzenchr
    Member

    Do we need a transformer for this or would an example suffice. FunctionTransformer(partial(torch.asarray, device="cuda:0")) is just one line of code.

  9. ogrisel commented on Apr 16, 2026

    @ogrisel
    Member

    The use of function transformer does not make it possible to update the pipeline to work without torch/GPU after fitting as stated in #33737 (comment).

  10. betatim commented on Apr 16, 2026

    @betatim
    MemberAuthor

    I think the main argument for a transformer is what Olivier wrote. Though I think the usability argument is quite high as well (for me): yes it is just one line but it is hard to remember (eg. you need to use partial, not lambda) and I can only just remember it (often I grep my iPython history for it instead of typing it out). This means my expectation of the average scikit-learn user would be "they can't remember it".

  11. lorentzenchr commented on Apr 16, 2026

    @lorentzenchr
    Member

    "they can't remember it".

    Then an example would help their memory as well as finding/remembering from sklearn.magic import MoveTo, wouldn't it?

    Note: I'm not against it, just challenging the feature request.

  12. thomasjpfan commented on Apr 18, 2026

    @thomasjpfan
    Member

    If it was only to simplify FunctionTransformer(torch.asarray, kw_args={"device": "mps"}), I do not think it is compelling enough to add a MoveTo transformer.

    I agree that having a __sklearn_array_api_convert__ is compelling enough to introduce a new transformer. What is the API contract for it?

    If __sklearn_array_api_convert__ can only return an array api compatible estimator, then it's kind of restrictive. I'm considering a GPU only estimator and converting it into a CPU only estimator (not array api compatible). For example, we can have GPUOnlyEstimator.__sklearn_for_array_namespace__(numpy) that returns an estimator that can only handle NumPy arrays. It gives the GPUOnlyEstimator developer the option to write accelerated CPU code.

  13. betatim commented on Apr 20, 2026

    @betatim
    MemberAuthor

    The question about "what is the contract for __sklearn_array_api_convert__?" is a good one. It was added as part of #33076 but has no documentation.

    The idea is to let estimators that have special demands/needs/weirdness handle converting themselves. __sklearn_array_api_convert__ gets called with the function that can convert an array (in the current namespace of the estimator, e.g. the one used during fit) to the target namespace. This means that __sklearn_array_api_convert__ has to return an estimator that works in the target namespace, but how it does that is left to it. I think this means it would support the use-case you have in mind Thomas. At least for me that is in the spirit of what it supports (the implementation might not but that would be a bug).

    Thinking about it, I am wondering if we need to pass more information to __sklearn_array_api_convert__ than just the conversion function, for example, the target namespace (name). We should try to implement MoveTo + Pipeline and your GPUOnlyEstimator to inform that discussion.

  14. david-cortes-intel commented on Apr 22, 2026

    @david-cortes-intel
    Contributor

    Commenting here since #33822 was closed.

    It appears that the current design of array API does not explicitly allow mixing non-array 'y' (e.g. pandas) with array API 'X' as shown in the code snippet from the description.

    But would be very useful for a feature like this if it did, since then a decision like "offload to GPU or not" could be handled independently of the rest of the steps in a transformer/estimator pipeline, without needing to change for example how classifiers treat categorical 'y' in order to accommodate GPU usage.

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

    Array APINeeds Decision

    Type

    No type

    Projects

    • Status
      Discussion

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions