Repository navigation
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.
This is an issue related to #34152 but is also a standalone issue.
While thinking about #34152 and working on #34324 I thought that it might be a good idea if the fitted attributes of an estimator were always Numpy arrays. The current plan is to store fitted attributes in the namespace/device of X.
Reasons to do this:
- users most often use fitted attributes for inspection/debugging/plotting. Having them in a consistent array namespace makes this easy to do. If the namespace is input dependent then you have to change your debugging/plotting code. Say you run the same script on a machine with a CUDA GPU and on your laptop with no GPU. While it is not difficult to use write code that uses
move_to()to conditionally bring the attributes to Numpy for plotting, it is tedious. - Today attributes are Numpy, by keeping them Numpy we remove one source of bugs/differences. Enabling array API by default would not change this
- Part of Make
validate_dataconvert inputs whenarray_api_dispatch=True#34324 that is not great/tricky is dealing with estimators that sometimes support array API. For example for some hyper-parameter values array API is supported and for some not. The tricky question: What should the type of the fitted attributes be? - You can
fitwith one array namespace/device andpredictwith a different one without any conversion - An estimator fitted with pytorch/CUDA can be unpickled on a machine without CUDA and even without pytorch
Something to check is how much overhead/performance loss we get in predict and other inference methods if we have to convert the fitted attributes relevant for predicting from Numpy to the array namespace of the input each time. Though I suspect that conversion is fast. It might add appreciable overhead if you are predicting on very few samples, but the absolute time will be short in those cases (and you could just use the CPU?). We would need to introduce a way to make it easy to convert fitted attributes to Numpy in each estimator to avoid lots of boilerplate. What are other reasons to not do this?
What do others think?
Activity
lorentzenchr commentedon Jul 30, 2026
I like the simplicity of the proposal.
What I'd like to understand better is
If you consider
Ridgewith this proposal, no matter whatXis,Ridge.coef_would be ndarray. But if you then callRidge.predict(X)with X a torch tensor on the GPU,coef_needs to be converted to torch and moved to the GPU.If this assessment is correct, then I think something like
Ridge.move_attr_to_device(X)is missing for someone how unpickles a fitted Ridge and wants to deploy it in production on a GPU.betatim commentedon Jul 30, 2026
My thinking was that the estimator will have to take care of moving the attributes for the user in the case you described. Every time
ridge.predict(X_torch_gpu)is called insidepredictwe'd move (a copy of)self.coef_to the right namespace and device. At the end of the callridge.coef_is still a ndarray. This means you can unpickle the model on a machine that has a CUDA device and use pytorch, independent of what you used for training.This is why I put the caveat of "need to investigate how much performance this costs". I hope not too much. The reason I'm optimistic is that we move
coef_to/from the GPU several times already when using the L-BFGS solver and that doesn't seem to cause a problem.For a production setup you might care about the overhead of the repeated conversion, in which case we might need something like
move_attr_to_namespace_and_device. Or maybe we'd have a meta estimator that takes care of this (kind of like an adaptor plug when you go on holiday)?ogrisel commentedon Aug 4, 2026
As discussed at the biweekly array API meeting, I am quite worried about the performance impact on predict/predict_proba/transform, especially in a cross-validation/hparam tuning setup.
lorentzenchr commentedon Aug 4, 2026
Let‘s not worry. Let‘s find out and make an informed decision.
Is there a voluteer to invent and run some benchmarks?
betatim commentedon Aug 5, 2026
I will try and put together some benchmarks based on
PCA. These are the cases we discussed in the meeting:Two other points to consider:
fit()andscore()coef_(or equivalent fitted attribute) in the numpy namespace or the namespace in which the work is being done?betatim commentedon Aug 6, 2026
I put up a PR with the modified code that implements a basic "store fitted attrs as Numpy" #34667
It is the result of asking AI to do the work, it looks reasonable. Maybe I wouldn't do it exactly this way, but it is probably good enough for benchmarking.
One thing I've learnt already while trying to benchmark things, and kind of already knew from this investigation, is that it seems for reasonable sizes of data (say 0-3MB for the fitted attributes) the transfer via
move_totakes something like 200us for Numpy->CUDA and about 350us for Numpy->MPS. It is much faster if you "move" numpy to numpy or numpy to torch-cpu. The other thing I realised is that you can argue that using pytorch-cuda for batches withn_samples=1is a waste. No matter if we move the attributes or not.Still double checking the numbers but they pass a first "smell test".
betatim commentedon Aug 11, 2026
https://gist.github.com/betatim/9c4ef2be3cb145fbd6d5b461a9cbd24b is a script that will compare storing attributes as numpy and in their native array type. It is already quite long so I didn't include a set of different shapes for
Xor how many samples are passed topredict. You can play with the settings for this at the top of the script. It will loop over a few different array namespace/device combinations.When I run this on my local machine with a A6000 GPU I get the following results:
What I am looking for is that there is a very small difference for the
numpyblock, ideally this should be exactly the same under the two scenarios. There is maybe a bit of extra work for making additional function calls. I might spend a bit more time investigating why thefitseems to have such a big difference of ~35ms. But I think this is an artefact/spurious.I am a little surprised to see
torch-cpudo better thannumpy. That seems surprising/weird. At least I can't explain why that should be.torch-cudadoes better again, which probably makes sense. Thetorch-mpscase is skipped because the machine isn't a macbook. Thecupycase is slower thantorch-cuda, which I think is due to cupy/cupy#10076 - well, will be fixed by that PR once it is released. At least from following the reasoning of my AI I am quite confident it tracked down the right bug/cause of the slow down.My big takeaway is that moving the fitted attributes is basically free. For very small
n_samplesinpredictyou can see the overhead, but I'd argue that you should just use Numpy for that anyway. Or batch things together. The only people who might notice this are people who care about high throughput on single samples. Again, my recommendation would be to use a CPU or batch samples.From looking at the above it seems like such a no brainer to store fitted attributes as Numpy that I feel like I must be missing something.
What do y'all think?
lorentzenchr commentedon Aug 12, 2026
@betatim Thanks for the benchmarks.
I‘d be very interested in a much simpler/harder one: timings of `move_to_device'
I guess the different hardware is the most important and most difficult one.
betatim commentedon Aug 13, 2026
I only timed from host to device (CPU -> GPU), I assume that it takes the same to go the other way? (Can check later)
For numpy and torch-cpu the only cost is the function calls involved in
move_to. It is negligible if you only call it once, but if you call it 100 times goes up to about 1.2ms. I tried 1 to 100 calls because an estimator has to transfer several arrays, not just one.For torch-mps I get the results below. They look at several scenarios. The first table is showing you how long it takes to move one array of different sizes. It compares using a "hand coded" function that only works for that particular library (e.g.
torch.asarray(x, device="cuda")) vs usingmove_to. For the "hand made" function it compares synchronising after each call or after a batch of calls.My take away is that using
move_tois fine, it doesn't cost too much. Moving ~100MB takes about 3ms. This means it is fast on an absolute scale, but could be slow relative to the work that happens after you calledmove_to. But if that is the case, then the total for "move + actual work" is still fast on an absolute scale. Let's say you move 100MB and then only take 1ms to do the actual work of the algorithm, the relative cost is huge but the absolute time taken is only ~4ms which is fast.The next two tables show what it looks like if you move 10MB in one go or split it up into several arrays. You can see moving many small bits takes longer. To the point where moving 10+ arrays uses many ms. The "one call" column is what we'd be doing in scikit-learn.
All the numbers above are from
torch-mps. Below here the same three tables in one go that are fromtorch-cudaand then after thatcupy.I haven't yet investigated why transferring 10x10MB seems to be faster on cupy than transferring 1x100MB. This seems odd.
I think the difference between
pytorch-cudaandcupyis explained by the fact that the cupy version I'm using doesn't support thedevice=keyword argument for DLPack. This meansmove_totries DLPack, catches the exception and then does something library specific.lorentzenchr commentedon Aug 13, 2026
This is a really great and insightful analysis. We indeed don‘t care too much about O(1) Python function calls (move_to without device transfer).
@scikit-learn/core-devs ping for visibility, insights and opinions welcome.
adam2392 commentedon Aug 13, 2026
Consolidation of attributes somehow imo is a good idea. My biggest pet peeve is if/else blocks to convert datatypes.
Playing devils advocate, the only issue I can foresee is if one plans on fitting 1000s of estimators, I guess this can add up(?) tho it seems that's still pretty bounded by O(1 second)? Lmk if that's incorrect.
thomasjpfan commentedon Aug 15, 2026
Even if there is minimum performance overhead, I am concerned with how implicit the API is. It's not clear that
est.fit(X_gpu_torch)will give you NumPy arrays as attributes. For example, in PyTorch, you need to be very explicit about where thennmodule lives:From reading the above, it's clear that
modelhas it's attributes stored in cuda.betatim commentedon Aug 18, 2026
I'd argue that what the type of the attributes is mostly convention. There is nothing implicit or explicit about either choice.
Why do you care to control where the attributes will be? No matter what input array type and device you use, the attributes will always be Numpy. It doesn't get more explicit than that.
Making them be Numpy means you can write code to inspect/print/plot/compute with them that will be the same if you run the script on your laptop without a GPU or a desktop that has a GPU.
It also means code written today (that has to assume that attributes are Numpy) will keep working. This fixes a wart/breaking change where enabling array API changes the type of fitted attributes for code that works today (an estimator with array API support and pytorch-cpu input currently has numpy attributes, but will suddenly have pyotrch-cpu attributes).
9 remaining items
betatim commentedon Sep 2, 2026
This is a sweep of
n_samplesfor three different scenarios on two different machines. I used my macbook which has a MPS device and a desktop that has a CUDA device. The three scenarios are:Xis numpyX,Xis MPS/CUDAXis MPS/CUDAThe pipeline used is
One plot shows the time for
fiton the pipeline and the other shows the time forpredict. The x axis showsn_samplesand the y axis shows the runtime (once in seconds, once in milliseconds).An interesting thing to look at is the difference between scenario (2) and (3). For
fitI find it hard to see a gap between the two. Forpredictthere is a visible gap of 1-2ms. There is a gap between the macbook and desktop that is presumably due to how many cores the machines have? I think the take away from thepredictplot for me is that you should be using your CPU for small batches/n_samplesand that the gap is small on a relative scale once we get to the point where inference on the CPU is slower than using an accelerator.It would be interesting to see what this looks like on other systems. I was surprised to see such a big difference for the numpy + numpy scenarios.
To run it you need #34667 and https://gist.github.com/betatim/8c92474df1f52ca81dee15a41f0cd712
adrinjalali commentedon Sep 7, 2026
Thinking about this, I think I'm okay with starting with numpy attributes everywhere (start, as in when / if we enable this by default), and then think of potential optimisations / making the estimator "warm" etc later.
betatim commentedon Sep 15, 2026
We discussed this at the array API/plugin meeting yesterday. At the meeting we concluded that we should implement this. From the comment by Adrin and reactions on it I think that is also the conclusion of this thread of discussion.
I will work on reviewing #34667 and getting it into a state where it can be reviewed by other humans. Right now it is the result of AI thinking of an API and implementing it. I spent minimal time reviewing it so far, which is why it is in draft mode.
david-cortes-intel commentedon Sep 23, 2026
@betatim Under this proposal, if the user uses
move_estimator_toto move to a non-default namespace (say, torch on GPU), would the resulting estimator also move its attributes on-demand during.predict()calls if the namespaces don't match? Would there be some way for the user to ensure that no data movement happens? For instance, when it comes to SYCL arrays, even if they are on the same device, arrays might have different queues which would trigger a "not same namespace" in checks likecheck_same_namespace.betatim commentedon Sep 29, 2026
I have only briefly thought about the case where the user moves the estimator to a particular namespace/device. In part because I am not sure what use-cases for it there are. It seems that moving the fitted attributes is not very expensive, when you are doing a large amount of compute in
predict,score,transform, etc. When the amount of compute is small it might not make sense to use a special device, just use numpy?With that out of the way, I think we can use
move_estimator_tofor the case where the user wants to control the namespace/device. With #35053 I think you canmove_estimator_toto your desired namespace/device and then most things become no-ops when you callmoved_estimator.predict(X_in_the_namespace_you_moved_to).Can you explain a bit more how/when
check_same_namespacewould deiced "not same namespace"? I was thinking that we won't need this function anymore because we move the attributes to matchX. But maybe whatever code that triggers this "not same namespace" decision is also used elsewhere?david-cortes-intel commentedon Sep 30, 2026
I see now in the linked PR that it is always calling 'move' functions without prior namespace checks.
My point is: for practical applications, one might want to create ML pipeline code in the most efficient manner possible, and test that it works as planned - i.e. verify that no data movement happens in tests, that the desired dtypes are seen in inputs and outputs, etc. For this, raising errors under some circumstances could be desirable.
Perhaps, but regardless, one might not want to silently find out that some online production service is moving data from CPU to GPU on every call when it was supposed to run on CPU, for instance.
betatim commentedon Oct 14, 2026
I would propose a mechanism based around
move_estimator_to()to achieve the use-case of having a pipeline that is already on the namespace/device it should be to avoid the data movement. For example in the code for a deployed inference server:optimal_for_mps_estwould have its fitted attributes moved to torch/"mps" so attributes won't have to be moved.Olivier propose an interesting idea yesterday: we could augment
move_toso that it works a bit like the warnings module of Python and provide a helper similar topytest.warns()that lets you test for warnings. Instead of asserting on warnings or the absence of warnings you could then assert that there was or was not any transfer of attributes.david-cortes-intel commentedon Oct 14, 2026
That sounds like a better idea.
But wouldn't it also trigger in cases where it might be expectable, like in here?
scikit-learn/sklearn/utils/class_weight.py
Line 92 in 0d4fe14
betatim commentedon Oct 14, 2026
Maybe we need a way to match only some movements, a bit like you can assert only on some warnings and/or the text in the warning message.
ogrisel commentedon Oct 22, 2026
By default
move_towould not raise any user facing warning. But when enabling a specificsklearn.condig_contextflag, it would allow specially written code (typically in a test suite) to write assertions about the presence or abscence of cross-namespace or cross-device data movement. We could even filter the record of data movement to write assertions that only consider movements of a specific shape or dtype for instance.david-cortes-intel commentedon Nov 16, 2026
@betatim Another topic here: how would this logic work with estimators like IncrementalPCA once they get array API support?
betatim commentedon Nov 18, 2026
Doing some quick benchmarking on an
IncrementalPCAthat claude converted to have array API suggests that the cost of repeated conversions is <5% compared to a array API version that keeps attributes in the namespace/device ofX. The round tripping cost is a larger percentage for cases where the CPU is faster than the GPU. This is on a A6000.Have you done some benchmarking on intel hardware?
david-cortes-intel commentedon Nov 18, 2026
I suppose that 5% could potentially vary depending on the sizes of batches and number of features. For instance, if it's incremented with a handful rows at a time and there's not too many columns, I imagine it could potentially become higher.
No. Did you do the benchmark by calling
move_estimator_toback and forth for the always-numpy version?betatim commentedon Nov 18, 2026
This is the script Claude generated for me, maybe you can reuse it.
Claude's benchmarking
david-cortes-intel commentedon Nov 19, 2026
Thanks. I'm not entirely sure how to use the script, but a few comments:
O(n_features^2 + n_rows*n_features), while the operations I think would beO(n_rows*n_features^3). It is conceivable that for some data shapes it could be a bad tradeoff to move things.I btw ran a slightly modified version of the script (with 10k rows only) on an nvidia H100, and it is the case that for most shapes of interest the overhead is around 6% (some reach 19% though), but I suppose it might be a bit different if it also considered calls to
.transform()and/or.get_covariance().