Repository navigation
Conversation
This adds a class that proxies access to fitted attributes and moves them to the required namespace/device on access.
|
One thing I only just thought of and need to ponder: how do we handle the case of a estimator method (say I'm not sure this is a problem that needs solving, but I am also not sure it doesn't need solving. |
virchan
left a comment
There was a problem hiding this comment.
Thank you for the PR!
I think I have a fix to the CI.
virchan
left a comment
There was a problem hiding this comment.
I think _fitted_attrs_like, _FittedAttrsLike, and their unit tests are good. I will continue with the rest of the PR later.
virchan
left a comment
There was a problem hiding this comment.
This is my understanding:
If a user fits a linear model on some X_train_xp, then the fitting is still performed in the same namespace and device as X_train_xp.
_fit_context now calls _fitted_attrs_as_numpy after fit returns. For LogisticRegression and LogisticRegressionCV, the fitted attributes are move_to NumPy arrays upon completion (2nd part of this PR). Other linear models still store them in the namespace and device of X_train_xp.
When calling decision_function on some X_test_xp2, _fitted_attrs_like creates a read-only view that:
- moves each fitted attribute of
estimatorto the namespace and device ofX_test_xp2the first time it is read. - caches the moved attribute in the view's
__dict__, so later reads are free.
Then, the decision values are computed in the same namespace and device as X_test_xp2 (1st part of this PR).
Overall, the PR LGTM, and I'm happy to approve this after a changelog is added, and the GPU CIs are green. Currently, the Intel ones are green (URL), and the CUDA is still queuing (URL).
I would place the changelog under API, but probably there are better tags.
|
@betatim I think this PR should update the array API narrative document to explain this new contract from a user's point of view. This will help reviewers be clear about the objectives of this PR before diving into the implementations details. |
|
For development, I would do it the other way around: first decide about the implementation (this PR, or another one), then dive into documentation (important to not foorget it). |
|
Overall I think it's a pretty good design, thank you for the thoughts you've put into it. AI found a few not-so-easy to fix bugs/concerns I think are worth addressing before moving forward. Fitted state read back during a fit. Attributes are converted each time a decorated fit returns, including nested fits. So a meta-estimator sees NumPy attributes on its sub-estimators while it's still computing with import torch
import sklearn
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
X, y = make_classification(n_classes=3, n_informative=3, random_state=0)
X, y = torch.asarray(X), torch.asarray(y)
with sklearn.config_context(array_api_dispatch=True):
# TypeError: Multiple namespaces for array inputs
CalibratedClassifierCV(
LogisticRegression(), method="temperature", ensemble=False
).fit(X, y)I opened betatim#2 on your branch as a proposed solution: convert only when the outermost fit returns (flag propagated to joblib workers like the config), make Code that reads Opt-in by class name. No way to get an error on a cross-namespace call anymore. With |
|
Opt-in by class name - I think the current way of doing it is fine, because it is meant to be gone/not needed anymore by the time of the next release. I thought about using a new flag/tag but not sure it really brings much compared to this list. For subclasses I am not even sure you'd want to inherit the flag, maybe the subclass does/doesn't support this -> we need to set this case by case? No way to get an error on a cross-namespace call anymore - for me this is a feature, not a bug. For production cases where you want to avoid this there will be Code that reads Fitted state read back during a fit - I will look at the PR, thanks for making it! I pondered the question of nesting and wasn't sure what to do. For iteration one I decided to not make nesting a special case -> conversion once |
A user might also want to sub-class scikit-learn estimators in their workflows. |
|
Thank you for your answers Tim! Opt-in by class name
Ah yes indeed, then fine for me. But how do we make sure it's really gone by the next release? 😅 No way to get an error on a cross-namespace call anymore
A user would first have to learn that scikit-learn stores fitted attributes as NumPy to follow this reasoning, so we'd have to make sure it's well documented and visible. But fair enough otherwise. Still, what do you think of an opt-in strict mode (off by default) that raises on implicit transfers? Maybe it's a useful thing to have for tests too? Maybe it's too painful to implement for what it's worth, or it could wait for a follow-up PR. Code that reads I checked what happens on main: With this PR, it's more uniform:
Fitted state read back during a fit I'll think about that again too, now that I'm starting to have an opinion of my own on this instead of just filtering & challenging AI opinions 😅 |
What do you mean? |
Something like: from sklearn.linear_model import LogisticRegression
class CustomLogisticRegression(LogisticRegression):
def predict(...):
... |
| items = ((f"{path}[{i}]", value) for i, value in enumerate(obj)) | ||
| elif ( | ||
| not isinstance(obj, type) | ||
| and type(obj).__module__.startswith("sklearn.") |
There was a problem hiding this comment.
What about third party libraries that want to implement array API semantics in a scikit-learn-compatible interface? Other libraries out there also run estimator checks from scikit-learn to test their compatibility with it.
| # Fit must not change constructor parameters, which also live in `vars()`. | ||
| params = estimator.get_params(deep=False) |
There was a problem hiding this comment.
Shouldn't this also apply during estimator movements with move_estimator_to?
| ) | ||
|
|
||
|
|
||
| def _move_state(*values, xp, device, dtype=None): |
There was a problem hiding this comment.
The name isn't great. Maybe a better name could be _move_to_compute - I'm trying to think of a name that tells the user when to use this function. To help keep the various different versions of "move to" separated. Ideas welcome. Maybe we can consolidate this with something else?
| # Fitted attributes are stored as NumPy arrays. Convert `classes_` here, | ||
| # rather than leaving it to `_fit_context`, because it is also handed to | ||
| # each `_CalibratedClassifier`, which the conversion does not look into. | ||
| self.classes_ = move_to(label_encoder_.classes_, xp=np, device="cpu") |
There was a problem hiding this comment.
Once LabelEncoder stores its fitted attributes as NumPy (betatim#11), label_encoder_.classes_ is already a NumPy array when LabelEncoder.fit returns, so this conversion and its comment become redundant. Whichever of the two PRs lands second should go back to:
| # Fitted attributes are stored as NumPy arrays. Convert `classes_` here, | |
| # rather than leaving it to `_fit_context`, because it is also handed to | |
| # each `_CalibratedClassifier`, which the conversion does not look into. | |
| self.classes_ = move_to(label_encoder_.classes_, xp=np, device="cpu") | |
| self.classes_ = label_encoder_.classes_ |
StefanieSenger
left a comment
There was a problem hiding this comment.
Thanks for taking this on, @betatim. I agree with the purpose of this PR. For now I only reviewed this at a high level, so I have not checked the details line by line.
Here are some early comments concerning weather we need _FittedAttrsLike at all and apply _convert_arrays only after the outermost fit has returned.
This PR is hard to review. Do you think we can split it off into separate parts? For instance along the lines of "train and infer on different devices" (PR1) versus "also enable pickling" (PR2 for later) to make it a bit easier?
| Attributes are moved when they are first read and the result is remembered, so | ||
| a method that uses the same attribute twice only pays for one transfer. |
There was a problem hiding this comment.
I don't understand the purpose of that. If I get this correctly, then this only remembers the converted attributes in the same call. We can use a local variable for this instead, no?
There was a problem hiding this comment.
The idea of having _FittedAttrsLike is so that we can change code from self.coefs_ to fitted.coefs_ (or a better name). So that it is a fairly mechanical rewrite and it easy to see if we missed something. We could use local variables and if I understand your proposal then it is similar to https://github.com/scikit-learn/scikit-learn/pull/34667/changes#diff-ccd606dafadeff9924fd14b1c68b34049f400eeb30c94c507c5143ee4ccfc86bR296-R303
I can't give a technical reason but somehow I prefer the way of doing it the way this PR (#35053) does it. One reason is that it means we don't have to write out a list of variables that we want to use at the top of a method and you can pass the _FittedAttrsLike instance to functions that are called from the method to share the cache (though that isn't used in this PR). One thing that is easy to do with the class is implement special behaviour like for classes_ (though you could also do that in the function based approach of #34667).
The cache only works for one call. Caching values across calls seems like an optimisation that we might want to make later, though I am not yet convinced it is worth it. People don't like the idea of repeatedly transferring values but so far no one has come with a benchmark that shows that this is detrimental. The benchmarks I've done don't show a significant cost for this behaviour and it makes the implementation a lot simpler. So until someone finds a good case where this is a real problem I am holding off on making the implementation more complex. Intellectually I don't love the repeated transfers, but the pragmatist in me wants to keep the implementation as simple as reasonably possible.
There was a problem hiding this comment.
Hm, the worst thing that can happen would be that X is kept as a fitted attribute (in KNN), is that correct? Do we keep larger matrixes often otherwise, do you know?
I wonder about this because I think that we could convert all the fitted attributes in the inference methods once the first one is requested. The computational cost lies in fit and for simplicity and maintainability it may be enough to convert all at once in a function call. This then would be equivalent to unpickling and then converting.
Did you think about this?
There was a problem hiding this comment.
Hm, the worst thing that can happen would be that
Xis kept as a fitted attribute (in KNN), is that correct? Do we keep larger matrixes often otherwise, do you know?I wonder about this because I think that we could convert all the fitted attributes in the inference methods once the first one is requested. The computational cost lies in
fitand for simplicity and maintainability it may be enough to convert all at once in a function call. This then would be equivalent to unpickling and then converting.Did you think about this?
I think that kind of approach would not play along with work happening in parallel on the freethreading front about not mutating state during .predict() and similar, if that line of work is to be undertaken.
There was a problem hiding this comment.
I think that kind of approach would not play along with work happening in parallel on the freethreading front about not mutating state during .predict() and similar, if that line of work is to be undertaken.
No, I didn't refer to move_estimator_to. I meant keeping converted attributes as local variables.
| "predicted indices into labels, and `move_to(self.classes_, ...)` " | ||
| "to compare `classes_` with labels." | ||
| ) | ||
| value = _move_state( |
There was a problem hiding this comment.
I am not sure if we really need _FittedAttrsLike as a class and wonder if we can call _move_state directly on the fitted attributes during predict or during plotting or pickling (not so sure about the pickling yet).
There was a problem hiding this comment.
We could. _FittedAttrsLike is meant to be a way to improve the ergonomics.
| return numpy.asarray(array) | ||
|
|
||
|
|
||
| def _convert_arrays(obj, converter, recurse_estimators=True): |
There was a problem hiding this comment.
_convert_arrays converts any array that is stored as an attribute on the object (recursively), but not all of the attributes may be needed for prediction.
Wouldn't it be enough to convert all those ending in underscore (_) which are the once we expose for other methods to use? (AI told me there is an exception in KNN (_fit_X), but this could be dealt with separately).
| Containers are recursed into. Estimators are cloned and recursed into via | ||
| their ``vars()``, so an array nested in e.g. a dict attribute of a | ||
| sub-estimator is converted too. Anything that is not an array, a container or | ||
| an estimator is left unchanged. |
There was a problem hiding this comment.
If I understand correctly, then _convert_arrays runs after each fit returns.
In my mind, this would be simpler if we walked down all the paths only after the outermost fit has finished (maybe similar to _non_numpy_array_paths). I think we then also wouldn't need to clone.
Do you think that's a valid alternative, @betatim?
There was a problem hiding this comment.
We could do that. A reason I prefer conversion after each estimator is done fitting is that it makes very clear what the type of each fitted attribute is when you interact with an estimator. It will always be a numpy array. No matter what the input array, whether the estimator is a scikit-learn one or from a third party library, or other cases.
Part of the exercise of making the PRs that convert all the other estimators is to get some data on how often we end up having to re-convert attributes and how costly that is:
class MyEstimator:
def fit(self, X, y):
sub_est = SomeOtherEstimator()
sub_est.fit(X, y)
# To use an attribute of `sub_est` together with `X` we need
# to re-convert it. Not pretty but maybe rare enough?
self.blah_ = somehow_combine(X, sub_est.foo_)
return selfclone is here because this function is meant to be used by move_estimator_to where I think it makes sense to return a copy/clone instead of modifying the original instance.
For _fit_context there is _fitted_attrs_as_numpy which modifies the actual instance.
There was a problem hiding this comment.
Thanks, I can see the problem this solves now. We only need the conversion because all fitted attributes must be NumPy arrays.
Part of the exercise of making the PRs that convert all the other estimators is to get some data on how often we end up having to re-convert attributes and how costly that is
Have you found how often the conversions happen in the estimators you have converted so far?
I'm not sure yet how to split it but I think the PR needs splitting. It has been growing since I started the PRs that convert all the estimators that have array API support in https://github.com/betatim/scikit-learn/pulls The point of doing that is seeing how much work it would be, as well as determining what shared infrastructure we need. All the shared infrastructure has been landing in this PR which has made it huge. |
StefanieSenger
left a comment
There was a problem hiding this comment.
Leaving some review comments on the documentation, @betatim. Thanks so far for your work.
| - Read attributes from ``self`` when only their metadata is needed (for example | ||
| ``self.coef_.ndim`` or ``self.classes_.shape[0]``). Metadata does not depend |
There was a problem hiding this comment.
| - Read attributes from ``self`` when only their metadata is needed (for example | |
| ``self.coef_.ndim`` or ``self.classes_.shape[0]``). Metadata does not depend | |
| - Read attributes from ``self`` when only library-independent facts are needed | |
| (for example ``self.coef_.ndim`` or ``self.classes_.shape[0]``). Those do not depend |
I would not call it metadata to not confuse users with metadata routing. This is a clumsy alternative, happy if you find something better.
(This also applies to the array-api.rst file in the use guide.)
| The helpers described here are private (they live in | ||
| ``sklearn/utils/_array_api.py``) and can change without deprecation. |
There was a problem hiding this comment.
As soon as we are sure on the design, we should expose them for downstream projects. Changing without deprecation is only fine as long as array API is expermental not after.
| Some computations that read fitted attributes run both during fitting, when the | ||
| attributes are still in the namespace of ``X``, and in inference methods, when | ||
| they are NumPy arrays. Do not pass "the estimator or a view of it" around to | ||
| handle both cases. Instead: | ||
|
|
||
| - Where possible, write the computation as a function of arrays, and let each | ||
| caller pass the arrays: ``self.precision_`` from fit or from a method without | ||
| ``X`` such as ``get_precision``, ``fitted.precision_`` from an inference | ||
| method. | ||
| - Otherwise, for example in a method that subclasses override, let the method | ||
| build its own view from the ``X`` it computes with, | ||
| ``fitted = _fitted_attrs_like(self, X)``. During fitting the attributes | ||
| already follow ``X``, so the view passes them through unchanged. |
There was a problem hiding this comment.
This is a bit hard to read. Here a suggestion to simplify this:
| Some computations that read fitted attributes run both during fitting, when the | |
| attributes are still in the namespace of ``X``, and in inference methods, when | |
| they are NumPy arrays. Do not pass "the estimator or a view of it" around to | |
| handle both cases. Instead: | |
| - Where possible, write the computation as a function of arrays, and let each | |
| caller pass the arrays: ``self.precision_`` from fit or from a method without | |
| ``X`` such as ``get_precision``, ``fitted.precision_`` from an inference | |
| method. | |
| - Otherwise, for example in a method that subclasses override, let the method | |
| build its own view from the ``X`` it computes with, | |
| ``fitted = _fitted_attrs_like(self, X)``. During fitting the attributes | |
| already follow ``X``, so the view passes them through unchanged. | |
| Some computations that read fitted attributes run both during fitting, when the | |
| attributes are still in the namespace of ``X``, and in inference methods, when they | |
| are NumPy arrays. Do not pass the estimator or a view of it around to handle both | |
| cases. Instead, make the shared helper take the array as an argument, and let the | |
| caller decide where to read it from:: | |
| def _scale(precision, factor): | |
| return precision * factor | |
| # In fit: read from self. | |
| _scale(self.precision_, factor) | |
| # In an inference method: read from the view. | |
| fitted = _fitted_attrs_like(self, X) | |
| _scale(fitted.precision_, factor) |
| Fitted state that is read back during fitting is a NumPy array, even if the | ||
| previous fit was done with a different namespace. With ``warm_start=True`` or in | ||
| ``partial_fit``, move the stored state to the namespace and device used for the |
There was a problem hiding this comment.
Simplification suggestion (since as a non-native, I had trouble with understanding "reading something back" and understanding "fitted state" as noun with an adjective):
| Fitted state that is read back during fitting is a NumPy array, even if the | |
| previous fit was done with a different namespace. With ``warm_start=True`` or in | |
| ``partial_fit``, move the stored state to the namespace and device used for the | |
| After `fit` returns, the stored attributes are NumPy arrays. If a later `fit` | |
| or `partial_fit` reads them (for example with `warm_start=Tru`e), they may | |
| be in a different namespace than the new `X`. In this case, move the stored | |
| state to the namespace and device used for the |
| previous fit was done with a different namespace. With ``warm_start=True`` or in | ||
| ``partial_fit``, move the stored state to the namespace and device used for the | ||
| computation with ``_move_state`` before using it. The same applies to other | ||
| arrays that a fit method computes with and writes back to the estimator, for |
There was a problem hiding this comment.
Same.
| arrays that a fit method computes with and writes back to the estimator, for | |
| arrays that a fit method computes with and stores on the estimator, for |
| --------------------------------------------- | ||
|
|
||
| Each call to ``predict``, ``transform`` or another method copies the fitted | ||
| attributes it needs to the device of its input. A copy is reused within that |
There was a problem hiding this comment.
"Input" here only means X. We should explicitly say so.
| negligible. When an estimator is called many times on small inputs, or has | ||
| large fitted attributes, the repeated copies can dominate the run time. | ||
|
|
||
| In that case, use ``move_estimator_to`` to store the fitted attributes on the |
There was a problem hiding this comment.
How can the user know if this is the case?
I would think for simplicity and efficiency, most people would simply do this as a default.
| Note that the `classes_` estimator attribute is a NumPy array, like all other | ||
| fitted attributes, which allows it to hold string class labels (see | ||
| :ref:`array_api_fitted_attributes`). |
There was a problem hiding this comment.
| Note that the `classes_` estimator attribute is a NumPy array, like all other | |
| fitted attributes, which allows it to hold string class labels (see | |
| :ref:`array_api_fitted_attributes`). |
Probably no need to mention.
| - an estimator fitted on a GPU can be unpickled on a machine without a GPU, or | ||
| without the array library it was fitted with. |
There was a problem hiding this comment.
I have found that array_api_extra has pickle_flatten and pickle_unflatten for that purpose already. I wonder if we can simplify this PR if we used it.
| - an estimator fitted on one device can be used on another, for example fitted | ||
| on a GPU and then used for prediction on a CPU, or the other way around; |
There was a problem hiding this comment.
That's not quite a consequence of this policy, but instead of the "everything follows X"-rule. I would not mention it here.
| - an estimator fitted on one device can be used on another, for example fitted | |
| on a GPU and then used for prediction on a CPU, or the other way around; |
Reference Issues/PRs
#34604
What does this implement/fix? Explain your changes.
This adds a class that proxies access to fitted attributes and moves them to the required namespace/device on access.
It is a way to implement what #34604 proposes. Namely store all fitted attributes as numpy arrays and then convert them to the namespace/device of
Xon the fly when they are used inpredict,score,transform, etc.The fundamental idea of this PR is to provide a class
_FittedAttrsLikethat can be used inpredictto give access to the attributes and take care of the conversions (and caching of those).The second part of this PR is
_fitted_attrs_as_numpy(estimator)which modifies an estimator in place and moves all of its fitted attributes to numpy. It is called at the end of the_fit_contextdecorator. This means we don't have to modifyfit/add boiler plate code tofit(or forget to do that)._fitted_attrs_as_numpyis almost equal tomove_estimator_to, the difference is that it modifies the estimator in place instead ofcloneing.The third part of this PR is adding a shortcut to
move_tofor the case were both source and target are numpy. Some of the functions we call and determinations we have to make as part of the general case inmove_toare "expensive". Because the_fitted_attrs_as_numpy()call lives in_fit_contextit gets applied to estimators with no array API support. So it felt worth adding this short cut to keep the overhead small. There is also #34840 which explores making micro optimisations formove_to().This PR converts a few classes to use this pattern. Mostly to avoid having a gigantic diff while we decide on the API. It also adjusts the common tests/checks. Until all estimators have been converted to this pattern we need a list to keep track which estimators use this pattern and which don't.
This is an alternative to #34667 which was a first attempt of implementing this. I think I prefer the API and ergonomics of this PR
AI usage disclosure
I used AI assistance for: