You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
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).
@jona-sassenhagen and I look at when linalg.svd, linalg.solve are faster for some array sizes and/or common MNE operations.
We test that the outputs are equivalent, to numerical precision (this will be a test, just like we have for CUDA).
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.
We replace linalg.svd and linalg.cholesky in our codebase with these private functions.
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.
I'd like to be a bit cautious here. Can we start with a code snippet
that leads to unnecessarily long computations? maybe we can just use
a smarter algorithm rather than adding such a big dependency.
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?
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.
can you share a full use case where in the pipeline the linalg.solve is the
bottleneck?
there are many ways to solve a linear system depending on problem
dimensions.
I'd to see numbers before jumping on adding cupy as a dependency of MNE.
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.
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?
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.
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.
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
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!
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.
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:
First, I updated mne.cuda to use asarray instead of arrayHERE and HERE.
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
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.
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.
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.
Activity
rkmaddox commentedon Aug 13, 2018
Yeah, big +1 from me. There are a couple models I've not dared to try to run because the solver couldn't deal.
agramfort commentedon Aug 14, 2018
larsoner commentedon Aug 14, 2018
IIRC @jona-sassenhagen and I (and @rkmaddox and I) already spent some time trying to optimize the
scipy.linalgcalls to no avail. But regardless we'll want some cases to test speed / show usefulness -- @jona-sassenhagen @rkmaddox can younp.random.RandomState(0).randnsome arrays of the right shapes andscipy.linalgthe right calls to show us the slowdowns that would be good to speed up?jona-sassenhagen commentedon Aug 14, 2018
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.
agramfort commentedon Aug 14, 2018
rkmaddox commentedon Aug 14, 2018
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:
This is doable, but takes a couple seconds on my laptop. But when I have two input stimuli,
n_factorsgoes up to 2, which takes 11 seconds.n_factors = 3takes 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.
jona-sassenhagen commentedon Aug 14, 2018
It's possible you'll end up being limited by GPU memory though, right?
rkmaddox commentedon Aug 14, 2018
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.
rkmaddox commentedon Aug 14, 2018
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.
jona-sassenhagen commentedon Aug 14, 2018
see:
http://nbviewer.jupyter.org/gist/jona-sassenhagen/a40a1e3d48bf7ac0f183ecd623aaae7a/cuda_test_solver.ipynb
I had more impressive results in the sparse case.
rkmaddox commentedon Aug 14, 2018
Interesting. That definitely does counts as modest. Thanks for testing it out.
rkmaddox commentedon Aug 14, 2018
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?
jona-sassenhagen commentedon Aug 14, 2018
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.
jona-sassenhagen commentedon Aug 14, 2018
... Ok, I'm using 4 features now and
(ignore the 1st GPU)
11 remaining items
scottrbrtsn commentedon Nov 21, 2024
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 getcupyxfor free when you installcupy.I've demonstrated potential viability in a notebook comparing
mne.resamplewhich usescupy.fftunder the hood, andcupyx.scipy.signal.resamplewhich has a modified version offft. TLDR: using zero-copy methods fromcuSignalcan cut the resample in half compared to the cuda resample frommne.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
fftcalcs 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 frommne.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.
larsoner commentedon Nov 22, 2024
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.scottrbrtsn commentedon Nov 22, 2024
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):
whereas (maybe unrelated) mne calculates a ratio using:
larsoner commentedon Nov 25, 2024
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
pocketfftfor resampling things were much closer than that but I guess not always!scottrbrtsn commentedon Nov 26, 2024
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
mnediscussing 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
mneandcuSignalto 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 themnecommunity can find an explanation I'd certainly love to hear the answer.I'm also curious, what other methods in
cuSignalmight be useful formneand then how the underlying technique could be applied uniquely formneto benefit in other ways.scottrbrtsn commentedon Nov 27, 2024
scottrbrtsn commentedon Nov 27, 2024
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:
mne.cudato useasarrayinstead ofarrayHERE and HERE.cupy.arraydefaults to copy=TruecupyxI 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
resampleand 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, replacecupy.arraywithcupy.asarray, and then pass in shared memory withget_shared_memwhen calling anything usingcuda. 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.larsoner commentedon Dec 2, 2024
PR welcome for this!
scottrbrtsn commentedon Dec 2, 2024
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.
larsoner commentedon Dec 2, 2024
If all you're doing is shared mem changes then this really shouldn't change. Unless
cupyxis 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
scottrbrtsn commentedon Dec 3, 2024
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
scottrbrtsn commentedon Dec 6, 2024
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.
larsoner commentedon Dec 6, 2024
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!
ENH: Add GPU acceleration exploration for permutation cluster tests