Skip to content

ENH: Use cupy #5439

Closed
Closed

Description

@larsoner

Apparently cupy has improved the linalg situation for CUDA-capable machines to the point we could benefit from using it.

I propose adding a MNE_USE_CUPY config var that people can set that automagically uses cupy when it's installed and useful to do so for linalg functions. Concretely this would mean:

  1. I create _safe_svd and a new _cholesky (or others if people think of some we use) to use cupy or scipy.linalg based on MNE_USE_CUPY (and cupy presence, just like cuda).
  2. @jona-sassenhagen and I look at when linalg.svd, linalg.solve are faster for some array sizes and/or common MNE operations.
  3. We test that the outputs are equivalent, to numerical precision (this will be a test, just like we have for CUDA).
  4. We test whether or not these actually work in parallel code. I suspect that they will not, in which case we can decide if n_jobs > 1 that we should not use cupy for linalg functions.
  5. We replace linalg.svd and linalg.cholesky in our codebase with these private functions.
  6. We extend to other functions like linalg.qr, etc. as necessary (maybe separate PR).

CC @rkmaddox I know you suffer at the hands of slow scipy.linalg sometimes, this might make your life easier.

EDIT: From @jona-sassenhagen in #5253.

Activity

  1. added this to the 0.17 milestone on Aug 12, 2018
  2. rkmaddox commented on Aug 13, 2018

    @rkmaddox
    Contributor

    Yeah, big +1 from me. There are a couple models I've not dared to try to run because the solver couldn't deal.

  3. agramfort commented on Aug 14, 2018

    @agramfort
    SponsorMember
  4. larsoner commented on Aug 14, 2018

    @larsoner
    MemberAuthor

    IIRC @jona-sassenhagen and I (and @rkmaddox and I) already spent some time trying to optimize the scipy.linalg calls to no avail. But regardless we'll want some cases to test speed / show usefulness -- @jona-sassenhagen @rkmaddox can you np.random.RandomState(0).randn some arrays of the right shapes and scipy.linalg the right calls to show us the slowdowns that would be good to speed up?

  5. jona-sassenhagen commented on Aug 14, 2018

    @jona-sassenhagen
    Contributor

    Tbh, a lot of our code is very fast indeed. Resampling, equalising epochs counts, ... have been massively sped up (by Eric). ICA has always been very fast. The Encoding module is very fast.

    The main linalg things that are slow IME: time-frequency decompositions of low frequencies; source localisation of long time series (raw objects). I don't know if CUDA would help here.

    But some linalg.solve calls that take a few seconds could still be sped up by an order of magnitude, which might e.g. improve permutation testing or temporal generalisation.

    I will see if I can whip up a few examples.

  6. agramfort commented on Aug 14, 2018

    @agramfort
    SponsorMember
  7. rkmaddox commented on Aug 14, 2018

    @rkmaddox
    Contributor

    My use case is looking at high sampling rate encoding models. This blows up pretty quickly as you add factors to the model, though doesn't seem to depend on the number of channels. So let's say sampling rate is 10000 Hz, the lags range from -100 to 300 ms. For one input factor one electrode, you get:

    n_lags = 4000
    n_factors = 1
    n = n_lags * n_factors
    n_ch = 1
    x = np.linalg.solve(np.random.randn(n, n), np.random.randn(n, n_ch))
    

    This is doable, but takes a couple seconds on my laptop. But when I have two input stimuli, n_factors goes up to 2, which takes 11 seconds. n_factors = 3 takes 31 seconds, 4 takes 67 seconds, and 5 takes 123 seconds.

    These numbers are kind of extreme, but well within the realm of possibility, especially for some of my future plans to look at interactions between model terms.

  8. jona-sassenhagen commented on Aug 14, 2018

    @jona-sassenhagen
    Contributor

    It's possible you'll end up being limited by GPU memory though, right?

  9. rkmaddox commented on Aug 14, 2018

    @rkmaddox
    Contributor

    Yeah, that's a fair point. Assuming the data fit in memory, I have no idea how much additional memory is needed for a solver.

  10. rkmaddox commented on Aug 14, 2018

    @rkmaddox
    Contributor

    Though I would say that if it's ever worth it to solve on the GPU, then it by definition would be with data that fit in memory.

  11. jona-sassenhagen commented on Aug 14, 2018

    @jona-sassenhagen
    Contributor

    see:

    http://nbviewer.jupyter.org/gist/jona-sassenhagen/a40a1e3d48bf7ac0f183ecd623aaae7a/cuda_test_solver.ipynb

    1. you see how comparatively smooth the implementation is
    2. on my Tesla K40 vs. 6-core i7, gains are rather modest
    3. my GPU RAM (12GB) can't handle n_factors = 5 in this case!

    I had more impressive results in the sparse case.

  12. rkmaddox commented on Aug 14, 2018

    @rkmaddox
    Contributor

    Interesting. That definitely does counts as modest. Thanks for testing it out.

  13. rkmaddox commented on Aug 14, 2018

    @rkmaddox
    Contributor

    The memory limit is interesting. Very rough calculations for 64-bit (8 byte) floats would say:
    (5 * 4000) ** 2 * 8 / 1e9 = 3.2 GB. So there must be a lot of memory overhead in the calculations? Is my math off?

  14. jona-sassenhagen commented on Aug 14, 2018

    @jona-sassenhagen
    Contributor

    Hm, my CUDA memory might not have been totally emptied. I am trying to see if I can make sure it's agains the full 11+ GB.

  15. jona-sassenhagen commented on Aug 14, 2018

    @jona-sassenhagen
    Contributor

    ... Ok, I'm using 4 features now and

    nvidia-smi
    Tue Aug 14 18:53:33 2018
    +-----------------------------------------------------------------------------+
    | NVIDIA-SMI 396.51                 Driver Version: 396.51                    |
    |-------------------------------+----------------------+----------------------+
    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
    |===============================+======================+======================|
    |   0  GeForce GT 720      Off  | 00000000:02:00.0 N/A |                  N/A |
    | N/A   39C    P8    N/A /  N/A |     41MiB /   978MiB |     N/A      Default |
    +-------------------------------+----------------------+----------------------+
    |   1  Tesla K40c          Off  | 00000000:03:00.0 Off |                    0 |
    | 30%   67C    P0   180W / 235W |   9905MiB / 11441MiB |    100%      Default |
    +-------------------------------+----------------------+----------------------+
    

    (ignore the 1st GPU)

  16. 11 remaining items

  17. scottrbrtsn commented on Nov 21, 2024

    @scottrbrtsn

    Hi, I'm wondering if revisiting the use of cuda (specifically zero-copy methods) might be worth the effort now, seeing as how techniques and hardware have evolved. There are zero-copy options using cuSignal which is now migrated to cupyx.scipy.signal. You get cupyx for free when you install cupy.

    I've demonstrated potential viability in a notebook comparing mne.resample which uses cupy.fft under the hood, and cupyx.scipy.signal.resample which has a modified version of fft. TLDR: using zero-copy methods from cuSignal can cut the resample in half compared to the cuda resample from mne.


    Disclaimer: I am not a signal processing expert, nor a cuda expert. I am simply passionate about learning more about both of these domains.

    Aside from cuda, I'm also curious how the fft calcs differ. I was able to output similar transformations as described last in the notebook. They just aren't nearly close enough to pass my slightly modified test from mne.


    I wrote a comment here as reference, and for discretion in case I'm missing something that might be more obvious. It just looks like there isn't much recent discussion in this project around cuda, assuming the bottleneck is data transfer.

    If it makes sense to create an issue for increased visibility I'd be happy to do so.

  18. larsoner commented on Nov 22, 2024

    @larsoner
    MemberAuthor

    Interesting! To make the comparisons more accurate, can you check with npad=0? MNE-Python by default pads the signals, which will make them longer, potentially change the FFT size, etc. It would also be worth checking for example with power-of-two size arrays in case you don't already, which should ensure that MNE and cupy pick the same FFT lengths.

  19. scottrbrtsn commented on Nov 22, 2024

    @scottrbrtsn

    I updated the comparisons based on your suggestions.


    biggest difference I notice so far (I'm wondering why the two transformations are close, but not close enough):

    The resampled signal starts at the same value as x but is sampled
    with a spacing of len(x) / num * (spacing of x). Because a
    Fourier method is used, the signal is assumed to be periodic.
    from cupyx.scipy.signal

    whereas (maybe unrelated) mne calculates a ratio using:

    def _resamp_ratio_len(up, down, n):
        ratio = float(up) / down
        return ratio, max(int(round(ratio * n)), 1)
    
  20. larsoner commented on Nov 25, 2024

    @larsoner
    MemberAuthor

    Interesting that it's 2x faster than ours, probably worth looking into why!

    Also good to know that even our implementation is an order of magnitude faster than CPU, I thought once we used pocketfft for resampling things were much closer than that but I guess not always!

  21. scottrbrtsn commented on Nov 26, 2024

    @scottrbrtsn

    Yes, that's exactly why I commented here. The gains illustrated in the article linked above demonstrate a similar difference. I am not very smart on any of these things, so in order to start to learn I simply wanted to compare myself.

    I did not see recent comms in mne discussing cuda, the most recent being concerned about data transfer being the bottleneck (i.e. if there isn't a lot of data to move to the gpu, and only transformation, then it doesn't make sense to use gpu). Finding a solution which avoids the data transfer seems like a great solution to many problems generally causing folks to not use gpu except for large datasets/calculations.

    How would you want to proceed? Either way I'm happy to continue to study both mne and cuSignal to possibly discover the nuances between the two implementations. I admit now, however, I'm starting mostly from zero on both fronts, so I may not arrive at an explanation any time soon and so will leave it up to you if the gain is worth the time. If anyone in in the mne community can find an explanation I'd certainly love to hear the answer.

    I'm also curious, what other methods in cuSignal might be useful for mne and then how the underlying technique could be applied uniquely for mne to benefit in other ways.

  22. scottrbrtsn commented on Nov 27, 2024

    @scottrbrtsn
    python -m cProfile -m mne_cupy_test | grep -v "0.000"
    Now using CUDA device 0
    Enabling CUDA with 15.46 GB available memory
    Using CUDA for FFT resampling
             2922935 function calls (2876931 primitive calls) in 3.849 seconds
    
       Ordered by: cumulative time
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
            1    0.009    0.009    2.790    2.790 mne_cupy_test.py:50(gpu_not_shared)
            1    0.001    0.001    2.238    2.238 filter.py:1932(_resample_fft)
            1    0.002    0.002    2.197    2.197 cuda.py:225(_setup_cuda_fft_resample)
            1    2.192    2.192    2.192    2.192 {method 'use' of 'cupy.cuda.device.Device' objects}
            1    0.001    0.001    0.188    0.188 _environment.py:501(_detect_duplicate_installation)
            1    0.001    0.001    0.036    0.036 cuda.py:314(_fft_resample)
            2    0.010    0.005    0.014    0.007 _fft.py:81(_exec_fft)
            1    0.013    0.013    0.013    0.013 {built-in method cupy_backends.cuda.libs.nvrtc.compileProgram}
            6    0.003    0.001    0.013    0.002 decoder.py:343(raw_decode)
            6    0.008    0.001    0.008    0.001 {built-in method _ctypes.dlopen}
            2    0.005    0.003    0.005    0.003 {method 'poll' of 'select.poll' objects}
            2    0.004    0.002    0.004    0.002 {built-in method cupy._core.core.array}
            3    0.003    0.001    0.003    0.001 {method 'load' of 'cupy.cuda.function.Module' objects}
            1    0.002    0.002    0.002    0.002 numeric.py:1172(roll)
            1    0.001    0.001    0.001    0.001 {method 'get' of 'cupy._core.core._ndarray_base' objects}
            1    0.001    0.001    0.001    0.001 {built-in method _posixsubprocess.fork_exec}
    
    python -m cProfile -m cusignal_test | grep -v "0.000"
             1825724 function calls (1795062 primitive calls) in 1.233 seconds
    
       Ordered by: cumulative time
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
            1    0.001    0.001    0.188    0.188 _environment.py:501(_detect_duplicate_installation)
           14    0.131    0.009    0.131    0.009 driver.py:324(safe_cuda_api_call)
            1    0.001    0.001    0.078    0.078 _continuous_distns.py:1(<module>)
            2    0.025    0.012    0.025    0.012 {built-in method cupy_backends.cuda.libs.nvrtc.compileProgram}
            1    0.001    0.001    0.017    0.017 _windows.py:1307(kaiser)
            6    0.007    0.001    0.007    0.001 {built-in method _ctypes.dlopen}
            2    0.005    0.002    0.005    0.002 {method 'poll' of 'select.poll' objects}
            2    0.003    0.001    0.004    0.002 _fft.py:81(_exec_fft)
            2    0.002    0.001    0.002    0.001 {built-in method cupy._core.core.array}
            1    0.001    0.001    0.001    0.001 _codata.py:1514(parse_constants_2018toXXXX)
            1    0.001    0.001    0.001    0.001 {built-in method _posixsubprocess.fork_exec}
            1    0.001    0.001    0.001    0.001 _iir_utils.py:1(<module>)
    
  23. scottrbrtsn commented on Nov 27, 2024

    @scottrbrtsn

    ok, I'm starting to fall into the "benchmarks are difficult" camp due to what the cuSignal article mentions as "cold vs warm performance differences" so I'm definitely not fully confident in my findings so far. Further, profiling in this circumstance is misleading, but gives some insight into the difference of what functions are called.

    That being said:

    1. First, I updated mne.cuda to use asarray instead of array HERE and HERE.
      1. cupy.assarray
      2. An array on the current device. If a is already on the device, no copy is performed.

      3. cupy.array defaults to copy=True
    2. Then I pass shared memory into mne.resample. This was leveraged from the explanation in cuSignal's quickstart
      1. since get-shared-memory didn't move over to cupyx I just copied the function into the test.

    Comparing back and forth, multiple times, it appears to be relatively consistently faster, and in line with cuSignal performance, without using cuSignal's resample and just leveraging cupy.asarray and the shared memory space.

    I'd still classify this as a theory. Some tests showed zero difference in execution time when profiling. When using timeit, I bumped up the number of runs to 100 to try to rule out cold start confounding runs.


    If this is truly the explanation, the solution is then anywhere in mne, replace cupy.array with cupy.asarray, and then pass in shared memory with get_shared_mem when calling anything using cuda. I'd be interested to see if there could be improvements even in some calculations which aren't leveraging cuda.


    all three of these runs still call cupy.asarray. The first is not passing in shared memory.

    python mne_cupy_test.py | grep -v Using
    Now using CUDA device 0
    Enabling CUDA with 15.46 GB available memory
    0.031362444409996894
    done
    
    python cusignal_test.py
    0.003023756019974826
    done
    
    python mne_shared_test.py | grep -v Using
    Now using CUDA device 0
    Enabling CUDA with 15.46 GB available memory
    0.007029709430016737
    done
    
  24. larsoner commented on Dec 2, 2024

    @larsoner
    MemberAuthor

    If this is truly the explanation, the solution is then anywhere in mne, replace cupy.array with cupy.asarray, and then pass in shared memory with get_shared_mem when calling anything using cuda.

    PR welcome for this!

  25. scottrbrtsn commented on Dec 2, 2024

    @scottrbrtsn

    Do you need an issue created or just go and link this one?

    And then I'll try to find the locations, list them, and then find a good way to replace them.

    I may need some eyes on whether or not tests pass. I need to rerun the tests with the change. For whatever reason I've seen the output, be close, but not close enough for the tolerance of the tests.

  26. larsoner commented on Dec 2, 2024

    @larsoner
    MemberAuthor

    For whatever reason I've seen the output, be close, but not close enough for the tolerance of the tests.

    If all you're doing is shared mem changes then this really shouldn't change. Unless cupyx is using float32 under the hood or something...

    But yes feel free to just open a WIP PR. I have a machine with CUDA I can use to test

  27. scottrbrtsn commented on Dec 3, 2024

    @scottrbrtsn

    Yea, no idea what I was doing before to fail the tests. They pass now.

    I implemented the simple route. We can discuss doing anything deeper in mne.

    #13002

  28. scottrbrtsn commented on Dec 6, 2024

    @scottrbrtsn

    boo.

    I went back to my original test. After aligning your test and mine as close as possible, against mne's main branch, using real mne data and not random signal data, the test does not hold anymore.

    sorry to distract you, I was led astray by the data I used to test.

  29. larsoner commented on Dec 6, 2024

    @larsoner
    MemberAuthor

    No problem, happy to revisit the old code and try to remember what it did 🙂

    Hope it was at least a bit useful to you as well!

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions