Skip to content

Raise if fit and predict use different array API namespaces or devices - #29313

Closed
jeromedockes wants to merge 33 commits into
scikit-learn:mainfrom
jeromedockes:check-fitted-same-namespace-device
Closed

jeromedockes wants to merge 33 commits into
scikit-learn:mainfrom
jeromedockes:check-fitted-same-namespace-device

Conversation

@jeromedockes

@jeromedockes jeromedockes commented Jun 20, 2024 •

Copy link
Copy Markdown
Contributor

What does this implement/fix? Explain your changes.

During the bi-weekly array API meeting it was decided that estimators should raise an error if their fitted attributes are not in the same array API namespace, or on the same device, as the inputs to predict() or transform().
Moreover, there should be a way to convert the attributes to the appropriate namespace and device to solve this error.

This pr adds _array_api.check_fitted_attribute to raise the error if necessary, and _array_api.convert_attributes to move the estimator to the namespace and device of a reference array.

>>> from sklearn.linear_model import Ridge
>>> import sklearn
>>> import torch
>>> from sklearn import datasets

>>> sklearn.set_config(array_api_dispatch=True)

>>> X, y = datasets.make_regression()
>>> X_torch = torch.asarray(X, device='cpu')
>>> y_torch = torch.asarray(y, device='cpu')
>>> ridge = Ridge().fit(X_torch, y_torch)
>>> type(ridge.predict(X_torch))
<class 'torch.Tensor'>
>>> ridge.predict(X)
Traceback (most recent call last):
    ...
ValueError: Inputs passed to Ridge.predict() must use the same array library and the same device as those passed to fit(). Array api namespaces used during fit (array_api_compat.torch) and predict (array_api_compat.numpy) differ. You can convert the estimator to the same library and device as X with: 'from sklearn.utils._array_api import convert_attributes; converted_estimator = convert_attributes(estimator, X)'
>>> from sklearn.utils._array_api import convert_attributes
>>> ridge = convert_attributes(ridge, X)
>>> type(ridge.predict(X))
<class 'numpy.ndarray'>
>>> ridge = convert_attributes(ridge, X_torch)
>>> type(ridge.predict(X_torch))
<class 'torch.Tensor'>

@github-actions

github-actions Bot commented Jun 20, 2024 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: f0fafc3. Link to the linter CI: here

Comment thread sklearn/utils/_array_api.py Outdated
return _estimator_with_converted_arrays(estimator, make_converter(ref_array))


def check_fitted_attribute(estimator, method_name, attr_name, X):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

during the meeting we said that this check could be added to utils.validation.check_is_fitted, but at some point we also said that array API support shouldn't modify scikit-learn's public API yet (which check_is_fitted is part of)

@jeromedockes jeromedockes changed the title [WIP] Raise if fit and predict use different array API namespaces or devices Raise if fit and predict use different array API namespaces or devices Jun 25, 2024
@ogrisel

ogrisel commented Jun 27, 2024

Copy link
Copy Markdown
Member

I think we should have a dedicated paragraph in the array API section of the changelog for 1.6 to explain that the error messages are more informative when passing different array types or devices at fit and prediction times.

Comment thread sklearn/linear_model/tests/test_base.py Resolved

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jeromedockes.

Maybe the documentation could be updated to specify this behavior of array API fitted estimators.

In addition, here a few suggestions for improvement below but otherwise, LGTM.

Comment thread sklearn/utils/_array_api.py Resolved
Comment thread sklearn/utils/_array_api.py Resolved
Comment thread sklearn/utils/_array_api.py Resolved
Comment thread sklearn/utils/_array_api.py Resolved
Comment thread sklearn/utils/_array_api.py Resolved
jeromedockes and others added 3 commits June 28, 2024 17:55
@jeromedockes

Copy link
Copy Markdown
Contributor Author

Thank you @ogrisel. IIRC we said in the meeting that this PR should add the converter and the check and add it to an example estimator -- ATM, it is done for LinearModel so AFAICT only the Ridge is affected. Should I apply the check to all other array api-compatible estimators in this PR?

@ogrisel

ogrisel commented Jun 29, 2024

Copy link
Copy Markdown
Member

As you prefer.

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a nice addition. But we do need a way to convert estimators between namespaces / devices as well (#26083)

Comment thread sklearn/linear_model/_base.py Outdated
from ..utils._array_api import (
_asarray_with_order,
_average,
check_fitted_attribute,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find the name confusing. Something like check_same_namespace would be more informative maybe?

Comment thread doc/whats_new/v1.6.rst Outdated
:class:`model_selection.HalvingRandomSearchCV` now support Array API
compatible inputs when their base estimators do. :pr:`27096` by :user:`Tim
Head <betatim>` and :user:`Olivier Grisel <ogrisel>`.
- :class:`linear_model.Ridge` now raises a more informative error message when arrays passed at

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also add this to doc/modules/array_api.rst (ideally in this PR?) I think it would be good for us as reviewers, contributors and users if we start writing down our conventions. I think we have a few now and they mostly just exist in our heads. Maybe this could be the starting topic

Comment thread sklearn/utils/_array_api.py Outdated

Attributes which are not arrays are left unchanged.
"""
return _estimator_with_converted_arrays(estimator, make_converter(ref_array))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you explain why we need make_converter? Could we have the same thing by having a function like convert_to(reference, X) which is used here a bit like _estimator_with_converted_arrays(estimator, functools.partial(convert_to, ref_array))?

I'm not sure which approach I prefer, so just trying to understand it at the moment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we have the same thing by having a function like convert_to(reference, X) which is used here a bit like _estimator_with_converted_arrays(estimator, functools.partial(convert_to, ref_array))?

yes, that would work just as well! I had make_converter return a function because I wanted to use the existing _estimator_with_converted_arrays, which expects a function. But we can also define convert_to and use partial as you suggest, I don't really have a preference

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(note both options will not have the same behavior when the dispatch_array_api config changes between the call to make_converter/partial and using the result, but this should probably be avoided in any case)

Comment thread sklearn/utils/_array_api.py Outdated
return convert


def convert_attributes(estimator, ref_array):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def convert_attributes(estimator, ref_array):
def convert_attributes(estimator, reference_array):

or maybe just reference? I somehow prefer to spell out things instead of using abbrvs (abbreviations) because it is easier to read.

Comment thread sklearn/utils/_array_api.py Outdated
return _estimator_with_converted_arrays(estimator, make_converter(ref_array))


def check_fitted_attribute(estimator, method_name, attr_name, X):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def check_fitted_attribute(estimator, method_name, attr_name, X):
def check_fitted_attribute(estimator, method_name, attribute, X):

Mostly motivated by trying to avoid abbreviations and it seems like attribute_name would be quite long and maybe not needed?

Comment thread sklearn/utils/_array_api.py Outdated
return _estimator_with_converted_arrays(estimator, make_converter(ref_array))


def check_fitted_attribute(estimator, method_name, attr_name, X):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion for a doc string:

Check that estimator's fitted(?) attribute is compatible with X.

Use this to check that an estimator was fitted using the same array namespace and device.
as X.

@betatim

betatim commented Jul 5, 2024

Copy link
Copy Markdown
Member

I like it. I left some comments mostly about naming of things. Finding a different name for check_fitted_attribute would be good, I like Adrin's suggestion. Something that tells you what the function checks for.

@betatim

betatim commented Jul 5, 2024

Copy link
Copy Markdown
Member

But we do need a way to convert estimators between namespaces / devices as well (#26083)

Yes, but also: can you expand on what you mean in this context?

The reason I ask is that the error message in this PR will tell you how to convert your estimator.

My current thinking/knowledge is that we have the following ideas on conversion:

  1. a function (like in this PR) that lets you convert an estimator
  2. the rule of "y follows X" - if y (or sample_weight or any(?) additional argument) are on a different namespace/device as X we will move it to match X (if we need to). The reasoning being that y is small and that transformers can't move it
  3. provide a transformer that can be placed in a pipeline that converts X to a particular namespace/device. This would allow you to implement a pipeline where some work happens on the CPU and some on the GPU (say).

(this is the kind of "convention" stuff I was referring to as things we should start writing down)

@adrinjalali

Copy link
Copy Markdown
Member

The reason I ask is that the error message in this PR will tell you how to convert your estimator.

Ah yes, I missed that. Two points there:

  • does it work on a pipeline? I'm not sure how to test the code so asking. But by looking at it, it doesn't seem to recurse on the sub-estimators and objects.
  • convert_attributes seem too close to the implementation detail. From the user's perspective, maybe something like move_estimator make more sense? We probably also want to allow users to actually pass a namespace / device if they want instead of X?

@betatim

betatim commented Jul 8, 2024

Copy link
Copy Markdown
Member

I don't think it will work on a pipeline, you'd have to convert the particular step in the pipeline. Which isn't great.

I wonder if we could easily make it recurse. Right now you could just iterate over all estimators in a pipeline and convert them. In the future where we have a MoveToNamespace transformer that moves X to a particular namespace it would have to understand that a "pytorch estimator" that is preceded by a MoveToNamespace(torch) step doesn't need converting.

A more user centred name would be good. move_estimator or convert_estimator?

@betatim

betatim commented Jul 12, 2024

Copy link
Copy Markdown
Member

I looked at how cuml deals with this and to my surprise it "just works". You can fit with a Numpy array and then predict with a cupy array or vice versa. I think internally it converts everything to a cupy array?

Maybe this is more of a discussion item than useful for this PR, but I didn't know where to put it.

@adrinjalali

Copy link
Copy Markdown
Member

Maybe this is more of a discussion item than useful for this PR, but I didn't know where to put it.

I think one of the discussion points we've had is: at least to start with, we don't want any implicit movement of data, or try to minimize it, between devices, cause it can cause performance regressions in odd ways. Once we have a better understanding of the array API support and how things work, we can discuss if / when it makes sense to make things implicit / automated, maybe?

@jeromedockes

Copy link
Copy Markdown
Contributor Author

I looked at how cuml deals with this and to my surprise it "just works".

that's interesting, but do you think it might depend on the estimator and the operations predict needs to perform? Also, AFAICT it is not the case for pytorch so it might be simpler not to rely on this behavior for any of the array api namespaces

@adrinjalali

Copy link
Copy Markdown
Member

Quote from #26083 (comment)

People are happy to have expensive hardware to train fast, but want to have cheap hardware to predict, and that means we need to be able to "move" across devices.

I don't think we have to support all combinations to start with, but having utility functions such as sklearn.convert_to_type which takes an object (Estimator) and tries to do the conversion makes sense. It also makes sense for it to fail on certain cases, with a nice message about what kind of conversion should work.

@ogrisel

ogrisel commented Dec 12, 2025 •

Copy link
Copy Markdown
Member

This PR has stalled a bit but in the meantime we now integrated a dlpack-based, cross-namespace and device conversion function, namely: move_to (#31829).

There are also fixes in the dlpack support that should be soon shipped with PyTorch 2.9.1 and NumPy 2.4.0 (in the mean time, our relies on to and from numpy/cpu based conversion as a fallback).

I think this PR should be synced with main and updated to leverage this new capability.

@betatim

betatim commented Jan 13, 2026

Copy link
Copy Markdown
Member

I'm attempting to refresh this PR with the latest changes from main.

@betatim

betatim commented Jan 14, 2026

Copy link
Copy Markdown
Member

Ahrg, I ran git push thinking it would ask me to configure a remote but it pushed to this PR's branch. This totally screwed up the diff :-/. I'll try to fix it but it will take a moment because I don't want to break it even more.

@betatim

betatim commented Jan 14, 2026

Copy link
Copy Markdown
Member

Fixed it. But I think I'll continue work in #33076

@betatim
betatim force-pushed the check-fitted-same-namespace-device branch from e5070ff to 6105654 Compare January 14, 2026 14:24
@ogrisel

ogrisel commented Jan 22, 2026

Copy link
Copy Markdown
Member

Closing in favor of #33076

@ogrisel ogrisel closed this Jan 22, 2026
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Array API Jan 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

4 participants