Skip to content

RFC Always store fitted attributes as Numpy #34604

Open

Description

@betatim

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

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

  1. 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.
  2. Today attributes are Numpy, by keeping them Numpy we remove one source of bugs/differences. Enabling array API by default would not change this
  3. Part of Make validate_data convert inputs when array_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?
  4. You can fit with one array namespace/device and predict with a different one without any conversion
  5. 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

  1. lorentzenchr commented on Jul 30, 2026

    @lorentzenchr
    Member

    I like the simplicity of the proposal.
    What I'd like to understand better is

    1. You can fit with one array namespace/device and predict with a different one without any conversion

    If you consider Ridge with this proposal, no matter what X is, Ridge.coef_ would be ndarray. But if you then call Ridge.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.

  2. betatim commented on Jul 30, 2026

    @betatim
    MemberAuthor

    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 inside predict we'd move (a copy of) self.coef_ to the right namespace and device. At the end of the call ridge.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)?

  3. ogrisel commented on Aug 4, 2026

    @ogrisel
    Member

    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.

  4. lorentzenchr commented on Aug 4, 2026

    @lorentzenchr
    Member

    Let‘s not worry. Let‘s find out and make an informed decision.
    Is there a voluteer to invent and run some benchmarks?

  5. betatim commented on Aug 5, 2026

    @betatim
    MemberAuthor

    I will try and put together some benchmarks based on PCA. These are the cases we discussed in the meeting:

    • benchmark case: PCA with large number of components
      • fit on n_samples >> n_features and n_components ~= n_features, then predict on small n_samples or n_samples=1
    • benchmark case: cross val Pipeline with PCA with n_features ~= n_components and then logistic regression
    • benchmark case: logistic regression with n_features ~= n_classes

    Two other points to consider:

    • what happens in a grid search setting? Constantly moving from CPU<>GPU between fit() and score()
    • what about scoring callbacks? The callbacks are passed a "semi fitted" estimators, would they see coef_ (or equivalent fitted attribute) in the numpy namespace or the namespace in which the work is being done?
  6. betatim commented on Aug 6, 2026

    @betatim
    MemberAuthor

    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_to takes 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 with n_samples=1 is a waste. No matter if we move the attributes or not.

    Still double checking the numbers but they pass a first "smell test".

  7. betatim commented on Aug 11, 2026

    @betatim
    MemberAuthor

    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 X or how many samples are passed to predict. 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:

    fit 200000 x 100, predict 1, score 10000, 3 classes, 20 components, float32
    best of 5, arms alternated
    
    numpy
                   as-is    as numpy   difference
      fit        402.6ms     438.5ms        +8.9%
      predict      410us       424us        +3.4%
      score        1.7ms       1.7ms        +2.0%
      predictions agree: yes
    
    torch-cpu
                   as-is    as numpy   difference
      fit        265.4ms     263.9ms        -0.5%
      predict      511us       595us       +16.5%
      score        1.9ms       2.0ms        +7.1%
      predictions agree: yes
    
    torch-cuda
                   as-is    as numpy   difference
      fit         20.4ms      20.8ms        +1.9%
      predict      531us       691us       +30.1%
      score        1.3ms       1.5ms       +12.6%
      predictions agree: yes
    
    torch-mps
      skipped: torch reports no MPS device
    
    cupy
                   as-is    as numpy   difference
      fit         90.2ms      90.6ms        +0.5%
      predict      574us       777us       +35.5%
      score        1.8ms       2.0ms       +11.8%
      predictions agree: yes
    

    What I am looking for is that there is a very small difference for the numpy block, 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 the fit seems to have such a big difference of ~35ms. But I think this is an artefact/spurious.

    I am a little surprised to see torch-cpu do better than numpy. That seems surprising/weird. At least I can't explain why that should be. torch-cuda does better again, which probably makes sense. The torch-mps case is skipped because the machine isn't a macbook. The cupy case is slower than torch-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_samples in predict you 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?

  8. lorentzenchr commented on Aug 12, 2026

    @lorentzenchr
    Member

    @betatim Thanks for the benchmarks.
    I‘d be very interested in a much simpler/harder one: timings of `move_to_device'

    • for a tiny (size<=10) and a large array (size>=100_000)
    • from CPU to GPU and vice-versa
    • for different array libs/types
    • for different often used hardware (nvidia gpu with x84, apple m3/4 macbook, …)

    I guess the different hardware is the most important and most difficult one.

  9. betatim commented on Aug 13, 2026

    @betatim
    MemberAuthor

    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 using move_to. For the "hand made" function it compares synchronising after each call or after a batch of calls.

    float32, best of 3 rounds of 7 reps (median), columns alternated within a row
    copy sync: one to_device per synchronize; copy amort: `batch` of them per synchronize
    move_to: the same copy through sklearn's helper; bookkeeping: move_to on an array already in place
    
      one move:
             bytes  batch   copy sync  copy amort     move_to  bookkeeping      copy rate
               4 B     50       172us       177us       228us         49us     22.7 KiB/s
           1.0 KiB     50       169us       176us       228us         49us      5.9 MiB/s
          10.2 KiB     50       179us       184us       242us         49us     55.8 MiB/s
         102.4 KiB     50       178us       184us       242us         49us    560.2 MiB/s
           1.0 MiB     50       215us       215us       278us         49us      4.5 GiB/s
          10.0 MiB     40       466us       455us       520us         49us     21.0 GiB/s
          33.0 MiB     12      1.09ms      1.09ms      1.17ms         49us     29.5 GiB/s
         100.0 MiB      4      2.83ms      2.86ms      2.93ms         49us     34.5 GiB/s
    

    My take away is that using move_to is 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 called move_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.

    separate: one move_to per piece; one call: one move_to with all pieces
      same 10.0 MiB, split across moves:
                     split    separate    one call   per piece   vs 1 move
              1 x 10.0 MiB       520us       519us       520us         0us
               2 x 5.0 MiB       829us       779us       414us       308us
               3 x 3.3 MiB      1.24ms      1.20ms       415us       724us
               4 x 2.5 MiB      1.58ms      1.48ms       395us      1.06ms
              10 x 1.0 MiB      2.97ms      2.69ms       297us      2.45ms
            32 x 320.0 KiB      8.09ms      7.06ms       253us      7.57ms
           100 x 102.4 KiB     24.16ms     21.89ms       242us     23.64ms
      same 100.0 MiB, split across moves:
                     split    separate    one call   per piece   vs 1 move
             1 x 100.0 MiB      2.78ms      2.57ms      2.78ms         0us
              2 x 50.0 MiB      3.23ms      3.19ms      1.62ms       454us
              3 x 33.3 MiB      4.96ms      4.87ms      1.65ms      2.18ms
              4 x 25.0 MiB      4.86ms      4.46ms      1.21ms      2.08ms
             10 x 10.0 MiB      7.25ms      6.87ms       725us      4.47ms
              32 x 3.1 MiB     15.44ms     13.15ms       483us     12.67ms
             100 x 1.0 MiB     31.30ms     27.50ms       313us     28.52ms
    

    All the numbers above are from torch-mps. Below here the same three tables in one go that are from torch-cuda and then after that cupy.

    torch-cuda
      one move:
             bytes  batch   copy sync  copy amort     move_to  bookkeeping      copy rate
               4 B     50         9us         6us        21us         12us    423.9 KiB/s
           1.0 KiB     50         9us         7us        22us         12us    106.8 MiB/s
          10.2 KiB     50        10us         7us        23us         12us    980.6 MiB/s
         102.4 KiB     50        18us        15us        31us         12us      5.5 GiB/s
           1.0 MiB     50        91us        87us       105us         12us     10.8 GiB/s
          10.0 MiB     40       457us       455us       474us         12us     21.4 GiB/s
          33.0 MiB     12      1.43ms      1.41ms      1.46ms         12us     22.6 GiB/s
         100.0 MiB      4      4.25ms      4.24ms      4.30ms         13us     23.0 GiB/s
      same 10.0 MiB, split across moves:
                     split    separate    one call   per piece   vs 1 move
              1 x 10.0 MiB       482us       478us       482us         0us
               2 x 5.0 MiB       548us       539us       274us        66us
               3 x 3.3 MiB       613us       601us       204us       131us
               4 x 2.5 MiB       675us       658us       169us       193us
              10 x 1.0 MiB      1.06ms      1.01ms       106us       577us
            32 x 320.0 KiB      1.59ms      1.40ms        50us      1.10ms
           100 x 102.4 KiB      3.16ms      2.61ms        32us      2.68ms
      same 100.0 MiB, split across moves:
                     split    separate    one call   per piece   vs 1 move
             1 x 100.0 MiB      4.32ms      4.32ms      4.32ms         0us
              2 x 50.0 MiB      4.39ms      4.38ms      2.20ms        71us
              3 x 33.3 MiB      4.42ms      4.43ms      1.47ms       101us
              4 x 25.0 MiB      4.48ms      4.48ms      1.12ms       155us
             10 x 10.0 MiB      4.88ms      4.84ms       488us       560us
              32 x 3.1 MiB      6.35ms      6.16ms       199us      2.03ms
             100 x 1.0 MiB     10.82ms     10.21ms       108us      6.50ms
    
    cupy
      one move:
             bytes  batch   copy sync  copy amort     move_to  bookkeeping      copy rate
               4 B     50        11us         8us        23us          9us    360.5 KiB/s
           1.0 KiB     50        11us         8us        23us          9us     91.3 MiB/s
          10.2 KiB     50        12us         9us        24us          9us    854.7 MiB/s
         102.4 KiB     50        18us        12us        27us          9us      5.5 GiB/s
           1.0 MiB     50        70us        54us        63us          9us     13.9 GiB/s
          10.0 MiB     40       575us       516us       527us          9us     17.0 GiB/s
          33.0 MiB     12      2.62ms      1.45ms      1.52ms          9us     12.3 GiB/s
         100.0 MiB      4      8.61ms      5.79ms      5.88ms         10us     11.3 GiB/s
      same 10.0 MiB, split across moves:
                     split    separate    one call   per piece   vs 1 move
              1 x 10.0 MiB       600us       598us       600us         0us
               2 x 5.0 MiB       515us       513us       257us       -85us
               3 x 3.3 MiB       517us       511us       172us       -83us
               4 x 2.5 MiB       563us       537us       141us       -37us
              10 x 1.0 MiB       646us       638us        65us        46us
            32 x 320.0 KiB      1.10ms      1.05ms        34us       500us
           100 x 102.4 KiB      2.73ms      2.56ms        27us      2.12ms
      same 100.0 MiB, split across moves:
                     split    separate    one call   per piece   vs 1 move
             1 x 100.0 MiB      8.71ms      8.68ms      8.71ms         0us
              2 x 50.0 MiB      6.80ms      6.80ms      3.40ms     -1.91ms
              3 x 33.3 MiB      6.29ms      6.27ms      2.10ms     -2.42ms
              4 x 25.0 MiB      6.17ms      6.18ms      1.54ms     -2.55ms
             10 x 10.0 MiB      5.02ms      4.91ms       502us     -3.70ms
              32 x 3.1 MiB      5.71ms      5.72ms       178us     -3.01ms
             100 x 1.0 MiB      7.48ms      7.33ms        75us     -1.23ms
    

    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-cuda and cupy is explained by the fact that the cupy version I'm using doesn't support the device= keyword argument for DLPack. This means move_to tries DLPack, catches the exception and then does something library specific.

  10. lorentzenchr commented on Aug 13, 2026

    @lorentzenchr
    Member

    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.

  11. adam2392 commented on Aug 13, 2026

    @adam2392
    Member

    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.

  12. thomasjpfan commented on Aug 15, 2026

    @thomasjpfan
    Member

    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 the nn module lives:

    model = MyModel()
    model.to("cuda")
    
    model(x_cuda)

    From reading the above, it's clear that model has it's attributes stored in cuda.

  13. betatim commented on Aug 18, 2026

    @betatim
    MemberAuthor

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

  14. 9 remaining items

  15. betatim commented on Sep 2, 2026

    @betatim
    MemberAuthor

    This is a sweep of n_samples for 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:

    1. fitted attributes in numpy, X is numpy
    2. fitted attributes in namespace of X, X is MPS/CUDA
    3. fitted attributes in numpy, X is MPS/CUDA

    The pipeline used is

    GridSearchCV(
        Pipeline(
            [
                ("scale", StandardScaler()),
                ("kernel", Nystroem(n_components=N_COMPONENTS, random_state=0)),
                ("clf", LogisticRegression(max_iter=MAX_ITER)),
            ]
        ),
        {"clf__C": [0.1, 1.0], "kernel__gamma": [None, 0.1]},
        cv=3,
    )

    One plot shows the time for fit on the pipeline and the other shows the time for predict. The x axis shows n_samples and 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 fit I find it hard to see a gap between the two. For predict there 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 the predict plot for me is that you should be using your CPU for small batches/n_samples and 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.

    Image Image

    To run it you need #34667 and https://gist.github.com/betatim/8c92474df1f52ca81dee15a41f0cd712

  16. adrinjalali commented on Sep 7, 2026

    @adrinjalali
    Member

    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.

  17. betatim commented on Sep 15, 2026

    @betatim
    MemberAuthor

    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.

  18. david-cortes-intel commented on Sep 23, 2026

    @david-cortes-intel
    Contributor

    @betatim Under this proposal, if the user uses move_estimator_to to 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 like check_same_namespace.

  19. betatim commented on Sep 29, 2026

    @betatim
    MemberAuthor

    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_to for the case where the user wants to control the namespace/device. With #35053 I think you can move_estimator_to to your desired namespace/device and then most things become no-ops when you call moved_estimator.predict(X_in_the_namespace_you_moved_to).

    Can you explain a bit more how/when check_same_namespace would deiced "not same namespace"? I was thinking that we won't need this function anymore because we move the attributes to match X. But maybe whatever code that triggers this "not same namespace" decision is also used elsewhere?

  20. david-cortes-intel commented on Sep 30, 2026

    @david-cortes-intel
    Contributor

    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.

    When the amount of compute is small it might not make sense to use a special device, just use numpy?

    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.

  21. betatim commented on Oct 14, 2026

    @betatim
    MemberAuthor

    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:

    import pickle
    import torch
    from sklearn.utils import move_estimator_to
    
    estimator = pickle.load("my_model.pkl")
    optimal_for_mps_est = move_estimator_to(estimator, xp=torch, device="mps")
    
    # No attribute movement
    optimal_for_mps_est.predict(X_torch_mps)

    optimal_for_mps_est would 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_to so that it works a bit like the warnings module of Python and provide a helper similar to pytest.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.

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

    @david-cortes-intel
    Contributor

    we could augment move_to so that it works a bit like the warnings module of Python

    That sounds like a better idea.

    But wouldn't it also trigger in cases where it might be expectable, like in here?

    sample_weight = move_to(sample_weight, xp=np, device="cpu")

  23. betatim commented on Oct 14, 2026

    @betatim
    MemberAuthor

    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.

  24. ogrisel commented on Oct 22, 2026

    @ogrisel
    Member

    By default move_to would not raise any user facing warning. But when enabling a specific sklearn.condig_context flag, 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.

  25. david-cortes-intel commented on Nov 16, 2026

    @david-cortes-intel
    Contributor

    @betatim Another topic here: how would this logic work with estimators like IncrementalPCA once they get array API support?

  26. betatim commented on Nov 18, 2026

    @betatim
    MemberAuthor

    Doing some quick benchmarking on an IncrementalPCA that 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 of X. 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?

  27. david-cortes-intel commented on Nov 18, 2026

    @david-cortes-intel
    Contributor

    Doing some quick benchmarking on an IncrementalPCA that 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 of X. The round tripping cost is a larger percentage for cases where the CPU is faster than the GPU. This is on a A6000.

    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.

    Have you done some benchmarking on intel hardware?

    No. Did you do the benchmark by calling move_estimator_to back and forth for the always-numpy version?

  28. betatim commented on Nov 18, 2026

    @betatim
    MemberAuthor

    This is the script Claude generated for me, maybe you can reuse it.

    Claude's benchmarking

    """Benchmark the cost of storing IncrementalPCA's fitted state as NumPy.
    
    Two array API ports of `IncrementalPCA.partial_fit` that do identical compute:
    
    - "keep": fitted state stays in the namespace/device of X between calls.
    - "numpy": mimics PR #35053. Every `partial_fit` call (including the ones
      `fit` makes for each batch, no nested-call optimisation) ends by moving all
      array attributes to NumPy, and the next call moves the state it reads back
      to the namespace/device of X.
    
    Usage: python bench_ipca_numpy_attrs.py [--device cuda] [--repeats 5]
    Requires torch and a scikit-learn with `move_to` (main or PR #35053).
    """
    
    import argparse
    import itertools
    import json
    import platform
    import time
    
    import numpy as np
    import torch
    
    import sklearn
    from sklearn.utils import gen_batches
    from sklearn.utils._array_api import get_namespace_and_device, move_to
    from sklearn.utils.extmath import _incremental_mean_and_var, svd_flip
    
    # State that partial_fit reads back on the next call.
    STATE = ("components_", "singular_values_", "mean_", "var_")
    
    
    class ArrayAPIIncrementalPCA:
        # Set from --svd-dtype in main().
        svd_in_input_dtype = True
    
        def __init__(self, n_components, batch_size, state_as_numpy):
            self.n_components = n_components
            self.batch_size = batch_size
            self.state_as_numpy = state_as_numpy
    
        def fit(self, X):
            for attr in (*STATE, "n_samples_seen_"):
                self.__dict__.pop(attr, None)
            for batch in gen_batches(
                X.shape[0], self.batch_size, min_batch_size=self.n_components
            ):
                self.partial_fit(X[batch])
            return self
    
        def partial_fit(self, X):
            xp, _, device = get_namespace_and_device(X)
            n_samples, n_features = X.shape
            input_dtype = X.dtype
            first_pass = not hasattr(self, "components_")
    
            if first_pass:
                n_seen = 0
                last_mean = xp.zeros(n_features, dtype=X.dtype, device=device)
                last_var = xp.zeros(n_features, dtype=X.dtype, device=device)
            else:
                n_seen = self.n_samples_seen_
                # This is the move that the "numpy" variant has to pay for. For
                # "keep" the state is already on device and move_to is a no-op.
                components, singular_values, last_mean, last_var = move_to(
                    *(getattr(self, a) for a in STATE), xp=xp, device=device
                )
    
            col_mean, col_var, n_total = _incremental_mean_and_var(
                X,
                last_mean=last_mean,
                last_variance=last_var,
                last_sample_count=xp.full(
                    (n_features,), n_seen, dtype=X.dtype, device=device
                ),
            )
            n_total = int(n_total[0])
    
            if first_pass:
                X = X - col_mean
            else:
                col_batch_mean = xp.mean(X, axis=0)
                X = X - col_batch_mean
                mean_correction = (n_seen / n_total * n_samples) ** 0.5 * (
                    last_mean - col_batch_mean
                )
                X = xp.concat(
                    (
                        xp.reshape(singular_values, (-1, 1)) * components,
                        X,
                        xp.reshape(mean_correction, (1, -1)),
                    ),
                    axis=0,
                )
    
            # `_incremental_mean_and_var` accumulates in float64, which promotes X.
            # sklearn's NumPy IncrementalPCA has the same promotion for all but the
            # first batch. Cast back: float64 SVDs are ~32x slower on consumer GPUs.
            if self.svd_in_input_dtype:
                X = xp.astype(X, input_dtype)
            U, S, Vt = xp.linalg.svd(X, full_matrices=False)
            U, Vt = svd_flip(U, Vt, u_based_decision=False)
            explained_variance = S**2 / (n_total - 1)
            k = self.n_components
    
            self.n_samples_seen_ = n_total
            self.components_ = Vt[:k, :]
            self.singular_values_ = S[:k]
            self.mean_ = col_mean
            self.var_ = col_var
            self.explained_variance_ = explained_variance[:k]
            self.explained_variance_ratio_ = S[:k] ** 2 / xp.sum(col_var * n_total)
            self.noise_variance_ = xp.mean(explained_variance[k:])
    
            if self.state_as_numpy:
                # What `_fitted_attrs_as_numpy` does at the end of `_fit_context`.
                for name, value in list(vars(self).items()):
                    if hasattr(value, "__array_namespace__") or isinstance(
                        value, torch.Tensor
                    ):
                        setattr(self, name, move_to(value, xp=np, device="cpu"))
            return self
    
    
    def sync(device):
        if device.startswith("cuda"):
            torch.cuda.synchronize()
    
    
    def time_it(fn, device, repeats):
        fn()  # warm up (cuSOLVER handles, allocator, ...)
        sync(device)
        times = []
        for _ in range(repeats):
            tic = time.perf_counter()
            fn()
            sync(device)
            times.append(time.perf_counter() - tic)
        return float(np.median(times))
    
    
    def run_case(X, n_components, batch_size, mode, device, repeats):
        results = {}
        for variant in (False, True):
            if mode == "fit":
    
                def fn(variant=variant):
                    ArrayAPIIncrementalPCA(n_components, batch_size, variant).fit(X)
    
            else:
                # Streaming: the user calls partial_fit with one batch at a time.
                batches = [
                    X[b]
                    for b in gen_batches(X.shape[0], batch_size, min_batch_size=n_components)
                ]
    
                def fn(variant=variant, batches=batches):
                    est = ArrayAPIIncrementalPCA(n_components, batch_size, variant)
                    for b in batches:
                        est.partial_fit(b)
    
            results["numpy" if variant else "keep"] = time_it(fn, device, repeats)
        return results
    
    
    def check_equivalent(X, n_components, batch_size):
        a = ArrayAPIIncrementalPCA(n_components, batch_size, False).fit(X)
        b = ArrayAPIIncrementalPCA(n_components, batch_size, True).fit(X)
        np.testing.assert_allclose(
            move_to(a.components_, xp=np, device="cpu"), b.components_, rtol=1e-4, atol=1e-5
        )
        assert isinstance(b.components_, np.ndarray)
        assert not isinstance(a.components_, np.ndarray)
    
    
    def time_svd(shape, device, dtype, gen, driver=None, calls=10):
        """Median time of one `torch.linalg.svd` call on a matrix of `shape`."""
        A = torch.randn(*shape, generator=gen, dtype=dtype).to(device)
        kwargs = {} if driver is None else {"driver": driver}
        torch.linalg.svd(A, full_matrices=False, **kwargs)  # warm up
        sync(device)
        times = []
        for _ in range(calls):
            tic = time.perf_counter()
            torch.linalg.svd(A, full_matrices=False, **kwargs)
            sync(device)
            times.append(time.perf_counter() - tic)
        return float(np.median(times))
    
    
    def run_baselines(grid, device, dtype, gen):
        """Context for the grid: SVD cost per batch and sklearn's NumPy IPCA."""
        from sklearn.decomposition import IncrementalPCA
    
        # (column label, driver, dtype). `driver` is only accepted for CUDA inputs,
        # None is torch's default.
        columns = [("default", None, dtype)]
        if device.startswith("cuda"):
            columns += [(d, d, dtype) for d in ("gesvd", "gesvdj", "gesvda")]
        if dtype != torch.float64:
            columns.append(("dflt f64", None, torch.float64))
    
        print(
            f"\nSVD of one batch matrix, (batch + n_comp + 1, n_features), "
            f"ms per call, {str(dtype).removeprefix('torch.')} unless noted"
        )
        header = f"{'shape':>14}" + "".join(f"{label:>10}" for label, _, _ in columns)
        print(header)
        print("-" * len(header))
        rows = []
        shapes = sorted({(bs + n_c + 1, n_f) for _, n_f, n_c, bs in grid})
        for shape in shapes:
            row = {"shape": shape}
            line = f"{str(shape):>14}"
            for label, driver, svd_dtype in columns:
                try:
                    t = time_svd(shape, device, svd_dtype, gen, driver=driver)
                    line += f"{t * 1e3:>10.2f}"
                except Exception as e:  # e.g. a driver not available in this build
                    t = None
                    line += f"{type(e).__name__[:9]:>10}"
                row[label] = t
            rows.append({"kind": "svd", **row})
            print(line, flush=True)
    
        print("\nsklearn IncrementalPCA.fit on NumPy (CPU), no array API dispatch")
        header = (
            f"{'n_samples':>10}{'n_feat':>8}{'n_comp':>8}{'batch':>7}"
            f"{'n_batch':>8}{'fit ms':>10}{'ms/batch':>10}"
        )
        print(header)
        print("-" * len(header))
        np_dtype = getattr(np, str(dtype).removeprefix("torch."))
        for n_samples, n_features, n_components, batch_size in grid:
            X = torch.randn(n_samples, n_features, generator=gen, dtype=dtype).numpy()
            X = X.astype(np_dtype, copy=False)
            n_batches = len(
                list(gen_batches(n_samples, batch_size, min_batch_size=n_components))
            )
    
            def fn():
                IncrementalPCA(n_components=n_components, batch_size=batch_size).fit(X)
    
            t = time_it(fn, "cpu", repeats=3)
            rows.append(
                dict(
                    kind="sklearn_numpy",
                    n_samples=n_samples,
                    n_features=n_features,
                    n_components=n_components,
                    batch_size=batch_size,
                    n_batches=n_batches,
                    fit_s=t,
                )
            )
            print(
                f"{n_samples:>10}{n_features:>8}{n_components:>8}{batch_size:>7}"
                f"{n_batches:>8}{t * 1e3:>10.1f}{t / n_batches * 1e3:>10.2f}",
                flush=True,
            )
        print()
        return rows
    
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("--device", default="cuda")
        parser.add_argument("--repeats", type=int, default=5)
        parser.add_argument("--dtype", default="float32")
        parser.add_argument("--quick", action="store_true", help="small grid smoke test")
        parser.add_argument("--json", help="write results to this file")
        parser.add_argument(
            "--n-features",
            type=int,
            nargs="+",
            default=[32, 256, 1024],
            help="restrict the grid to these numbers of features",
        )
        parser.add_argument(
            "--baselines-only",
            action="store_true",
            help="only run the SVD and NumPy reference timings",
        )
        parser.add_argument(
            "--svd-dtype",
            choices=["input", "promoted"],
            default="input",
            help=(
                "'input': SVD in the dtype of X. 'promoted': let the float64 "
                "statistics promote the SVD input (what the first run measured)"
            ),
        )
        args = parser.parse_args()
        ArrayAPIIncrementalPCA.svd_in_input_dtype = args.svd_dtype == "input"
    
        dtype = getattr(torch, args.dtype)
        gen = torch.Generator(device="cpu").manual_seed(0)
    
        if args.quick:
            grid = [(2_000, 32, 5, 64)]
        else:
            # (n_samples, n_features, n_components, batch_size)
            grid = []
            for n_features in args.n_features:
                for batch_size in sorted({128, 1024, 5 * n_features}):
                    for n_components in (10, min(100, n_features // 2)):
                        grid.append((50_000, n_features, n_components, batch_size))
            grid = sorted(set(grid))
    
        print(
            f"sklearn {sklearn.__version__}, torch {torch.__version__}, "
            f"device={args.device}"
            + (f" ({torch.cuda.get_device_name()})" if args.device.startswith("cuda") else "")
            + f", host={platform.node()}, dtype={args.dtype}"
        )
    
        baseline_rows = run_baselines(grid, args.device, dtype, gen)
        if args.json:
            with open(args.json, "w") as f:
                json.dump({"baselines": baseline_rows}, f, indent=1)
        if args.baselines_only:
            return
    
        rows = []
        with sklearn.config_context(array_api_dispatch=True):
            n_s, n_f, n_c, bs = grid[0]
            X = torch.randn(n_s, n_f, generator=gen, dtype=dtype).to(args.device)
            check_equivalent(X, n_c, bs)
    
            header = (
                f"{'mode':<12}{'n_samples':>10}{'n_feat':>8}{'n_comp':>8}{'batch':>7}"
                f"{'n_batch':>8}{'keep ms':>10}{'numpy ms':>10}{'ratio':>7}"
                f"{'Δ/batch µs':>12}"
            )
            print(header)
            print("-" * len(header))
            for (n_samples, n_features, n_components, batch_size), mode in itertools.product(
                grid, ("fit", "partial_fit")
            ):
                X = torch.randn(n_samples, n_features, generator=gen, dtype=dtype).to(
                    args.device
                )
                n_batches = len(
                    list(gen_batches(n_samples, batch_size, min_batch_size=n_components))
                )
                r = run_case(X, n_components, batch_size, mode, args.device, args.repeats)
                delta_us = (r["numpy"] - r["keep"]) / n_batches * 1e6
                row = dict(
                    mode=mode,
                    n_samples=n_samples,
                    n_features=n_features,
                    n_components=n_components,
                    batch_size=batch_size,
                    n_batches=n_batches,
                    keep_s=r["keep"],
                    numpy_s=r["numpy"],
                )
                rows.append(row)
                print(
                    f"{mode:<12}{n_samples:>10}{n_features:>8}{n_components:>8}"
                    f"{batch_size:>7}{n_batches:>8}{r['keep'] * 1e3:>10.1f}"
                    f"{r['numpy'] * 1e3:>10.1f}{r['numpy'] / r['keep']:>7.2f}"
                    f"{delta_us:>12.0f}",
                    flush=True,
                )
    
        if args.json:
            with open(args.json, "w") as f:
                json.dump({"baselines": baseline_rows, "grid": rows}, f, indent=1)
    
    
    if __name__ == "__main__":
        main()

  29. david-cortes-intel commented on Nov 19, 2026

    @david-cortes-intel
    Contributor

    Thanks. I'm not entirely sure how to use the script, but a few comments:

    • I think SVD as implement in LAPACK is an iterative procedure with numeric tolerances whose running time depends on the distribution of singular values, so I suspect the example here might not be entirely representative.
    • The variables of interest here would be rows in a batch, and number of features. The data movements would have to be O(n_features^2 + n_rows*n_features), while the operations I think would be O(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().

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions