Skip to content

Store all fitted attributes as Numpy arrays - #35053

Open
betatim wants to merge 33 commits into
scikit-learn:mainfrom
betatim:store-all-attrs-as-numpy
Open

betatim wants to merge 33 commits into
scikit-learn:mainfrom
betatim:store-all-attrs-as-numpy

Conversation

@betatim

@betatim betatim commented Sep 29, 2026

Copy link
Copy Markdown
Member

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 X on the fly when they are used in predict, score, transform, etc.

The fundamental idea of this PR is to provide a class _FittedAttrsLike that can be used in predict to give access to the attributes and take care of the conversions (and caching of those).

def predict(self, X):
  # Use `fitted` like `self` to access fitted attributes
  fitted = _fitted_attrs_like(self, X)
  # This used to be:  return X @ self.coef_.T + self.intercept_
  return X @ fitted.coef_.T + fitted.intercept_

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_context decorator. This means we don't have to modify fit/add boiler plate code to fit (or forget to do that). _fitted_attrs_as_numpy is almost equal to move_estimator_to, the difference is that it modifies the estimator in place instead of cloneing.

The third part of this PR is adding a shortcut to move_to for 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 in move_to are "expensive". Because the _fitted_attrs_as_numpy() call lives in _fit_context it 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 for move_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:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation

This adds a class that proxies access to fitted attributes and moves
them to the required namespace/device on access.
@betatim

betatim commented Sep 29, 2026

Copy link
Copy Markdown
Member Author

One thing I only just thought of and need to ponder: how do we handle the case of a estimator method (say score) that access attribute foo_ itself and also calls predict which also accesses foo_. Right now foo_ would be transferred twice because the _FittedAttrsLike instance lives inside each methods scope.

I'm not sure this is a problem that needs solving, but I am also not sure it doesn't need solving.

@virchan virchan 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.

Thank you for the PR!

I think I have a fix to the CI.

Comment thread sklearn/utils/estimator_checks.py Resolved

@virchan virchan 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 _fitted_attrs_like, _FittedAttrsLike, and their unit tests are good. I will continue with the rest of the PR later.

Comment thread sklearn/utils/_array_api.py Resolved

@virchan virchan 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.

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:

  1. moves each fitted attribute of estimator to the namespace and device of X_test_xp2 the first time it is read.
  2. 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.

@ogrisel

ogrisel commented Oct 5, 2026

Copy link
Copy Markdown
Member

@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.

@ogrisel ogrisel moved this to PR waiting for reviews in Labs Oct 5, 2026
@lorentzenchr

Copy link
Copy Markdown
Member

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).

@cakedev0

cakedev0 commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

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 X on array API, and partial_fit / warm_start read back NumPy state. For instance this works on main and fails on this PR:

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 partial_fit move its running state to X first, and add a common check with array_api_strict on "device1" so forgetting it raises. StandardScaler is converted there as an example.


Code that reads classes_ together with predictions. Calling cross_val_predict(LogisticRegression(), X_torch, y_torch, method="predict_proba") directly also fails: _enforce_prediction_order gets NumPy classes_ and torch predictions. The fix is easy, but I think it's a whole class of bugs: there is probably more code that assumes fitted attributes and outputs share a namespace (calibration, multiclass meta-estimators, labels=clf.classes_ in metrics, ...). No test covers these paths today, which is why CI is green.


Opt-in by class name. type(estimator).__name__ in _NUMPY_FITTED_ATTRS skips subclasses (class MyLR(LogisticRegression) keeps torch attributes) and matches any unrelated class with the same name. I'd use a class attribute or a tag instead, even if it's temporary.


No way to get an error on a cross-namespace call anymore. With check_same_namespace gone, a mismatch is a silent transfer. I think @david-cortes-intel's point in #34604 is valid: in production you might want an error rather than finding out later that every call copies data to/from the GPU. A strict option (maybe just for testing) would be cheap to add, WDYT?

@betatim

betatim commented Oct 7, 2026

Copy link
Copy Markdown
Member Author

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 move_estimator_to. I'm not sure emitting a warning every time predict (and friends) are called with a "cross namespace" X is a good thing to do. It will be very noisy and for most people there is no downside. This means the way to find out about move_estimator_to is for the user to think "I see a performance problem, it is because of these transfers, let me find out what the solution is", that seems fine to me. I don't think there is a big potential for users to be surprised, cross namespace use always leads to a transfer and to prevent it you need to use move_estimator_to.

Code that reads classes_ together with predictions - good point. I think we will need to do quite a bit of work to make sure all the code that exists today and assume the old convention is updated. This problem might already exist though, because classes_ can be numpy already today for string labels (I think)

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 fit returns. The nice thing about this is that a meta estimator doesn't need to know whether the sub estimator supports array API or not, because the attributes will always be numpy. Independent of the input namespace and independent of the sub-estimator. But it does mean we make more transfers and need to have code that deals with X and the sub-estimator attributes being on different namespaces. I need to think more to figure out what my opinion is, I think :-/

@david-cortes-intel

Copy link
Copy Markdown
Contributor

For subclasses I am not even sure you'd want to inherit the flag

A user might also want to sub-class scikit-learn estimators in their workflows.

@cakedev0

cakedev0 commented Oct 7, 2026

Copy link
Copy Markdown
Member

Thank you for your answers Tim!

Opt-in by class name

it is meant to be gone/not needed anymore by the time of the next release.

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

the user to think "I see a performance problem, it is because of these transfers, let me find out what the solution is"

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 classes_ together with predictions

I checked what happens on main: classes_ follows the namespace of y, so it only matches the predictions when y and X share a namespace (string labels being the main exception), which is not a great pattern I'd say. That exception is handled explicitly where it matters (cross_val_predict label-encodes and moves y to the namespace of X, LinearClassifierMixin.predict handles string classes_ on its own).

With this PR, it's more uniform: classes_ is always NumPy (it's a good argument for this PR direction overall). But that means that:

  • any code that uses classes_ together with predictions should now move classes_ into the namespace of the predictions. For now LinearClassifierMixin.predict does it the other way around (moves the indices to the namespace of classes_, then the result back), which works but transfers n_samples-sized arrays instead of classes_.
  • we need a test that enforces this ⬆️. For example, run cross_val_predict with predict_proba / decision_function, CalibratedClassifierCV, and the multiclass meta-estimators on converted estimators with array API inputs.

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 😅

@cakedev0

cakedev0 commented Oct 7, 2026

Copy link
Copy Markdown
Member

@david-cortes-intel

A user might also want to sub-class scikit-learn estimators in their workflows.

What do you mean?

@david-cortes-intel

Copy link
Copy Markdown
Contributor

@david-cortes-intel

A user might also want to sub-class scikit-learn estimators in their workflows.

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.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +1150 to +1151
# Fit must not change constructor parameters, which also live in `vars()`.
params = estimator.get_params(deep=False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't this also apply during estimator movements with move_estimator_to?

)


def _move_state(*values, xp, device, dtype=None):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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?

Comment thread sklearn/calibration.py
Comment on lines +484 to +487
# 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")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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:

Suggested change
# 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 StefanieSenger 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 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?

Comment on lines +1251 to +1252
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.

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 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?

@betatim betatim Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

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.

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

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.

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 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(

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 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).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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):

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.

_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).

Comment on lines +1034 to +1037
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.

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.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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 self

clone 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.

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, 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?

@betatim

betatim commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

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?

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.

@betatim betatim removed this from the 1.10 milestone Nov 26, 2026

@StefanieSenger StefanieSenger 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.

Leaving some review comments on the documentation, @betatim. Thanks so far for your work.

Comment on lines +94 to +95
- Read attributes from ``self`` when only their metadata is needed (for example
``self.coef_.ndim`` or ``self.classes_.shape[0]``). Metadata does not depend

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
- 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.)

Comment on lines +13 to +14
The helpers described here are private (they live in
``sklearn/utils/_array_api.py``) and can change without deprecation.

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.

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.

Comment on lines +108 to +120
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.

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.

This is a bit hard to read. Here a suggestion to simplify this:

Suggested change
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)

Comment on lines +125 to +127
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

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.

Simplification suggestion (since as a non-native, I had trouble with understanding "reading something back" and understanding "fitted state" as noun with an adjective):

Suggested change
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

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.

Same.

Suggested change
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

Comment thread doc/modules/array_api.rst
---------------------------------------------

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

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.

"Input" here only means X. We should explicitly say so.

Comment thread doc/modules/array_api.rst
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

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.

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.

Comment thread doc/modules/array_api.rst
Comment on lines +331 to +333
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`).

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
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.

Comment thread doc/modules/array_api.rst
Comment on lines +395 to +396
- an estimator fitted on a GPU can be unpickled on a machine without a GPU, or
without the array library it was fitted with.

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 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.

Comment thread doc/modules/array_api.rst
Comment on lines +393 to +394
- 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;

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.

That's not quite a consequence of this policy, but instead of the "everything follows X"-rule. I would not mention it here.

Suggested change
- 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;

This branch has not been deployed

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

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

7 participants