mne-python icon indicating copy to clipboard operation
mne-python copied to clipboard

Epoch-ing too slow when #events is large..

Open haribharadwaj opened this issue 11 years ago • 35 comments

So I have several ABR dataset where I have about 8000 trials. Epoching is way too slow and I suspect that the issue is related to not pre-allocating memory in _get_data_from_disk and growing the _data array one epoch at a time. When I don't do preload=True, when I eventually have to average, epochs.average() is too slow.

Am I missing something or is there room to speed things up?

haribharadwaj avatar May 01 '15 01:05 haribharadwaj

The problem is peak-to-peak artifact rejection. 8000 trials is really big, I think you're hitting the limits of the technology that's currently used. We hava lots of looping and single-trial operations which don't scale well if you have many trials. Not sure what we can do. Epochs.average is slow because it's built in a memory-saving way, accumulating (sum VS std) over trials and subsequently dividing by the number of trials instead of using numpy array methods directly. Of course you can build yourself a work-aroud based on RawArray and EpochsArray, if all fits into memory.

2015-05-01 3:51 GMT+02:00 Hari Bharadwaj [email protected]:

So I have several ABR dataset where I have about 8000 trials. Epoching is way too slow and I suspect that the issue is related to not pre-allocating memory in _get_data_from_disk and growing the _data array one epoch at a time. When I don't do preload=True, when I eventually have to average, epochs.average() is too slow.

Am I missing something or is there room to speed things up?

— Reply to this email directly or view it on GitHub https://github.com/mne-tools/mne-python/issues/2049.

dengemann avatar May 01 '15 01:05 dengemann

Ah Ok.. the thing is the trials are really short (15 ms)...so memory is not really an issue at all. I'll play with EpochsArray.

That said, don't you think peak-to-peak based rejection can be vectorized?

haribharadwaj avatar May 01 '15 02:05 haribharadwaj

That said, don't you think peak-to-peak based rejection can be vectorized?

Not sure this is in reach.

Ah Ok.. the thing is the trials are really short (15 ms)

Ah Ok ..... btw. what does "long" mean, can you share benchmarks (time, system environment).

2015-05-01 4:37 GMT+02:00 Hari Bharadwaj [email protected]:

Ah Ok.. the thing is the trials are really short (15 ms)...so memory is not really an issue at all. I'll play with EpochsArray.

That said, don't you think peak-to-peak based rejection can be vectorized?

— Reply to this email directly or view it on GitHub https://github.com/mne-tools/mne-python/issues/2049#issuecomment-98029457 .

dengemann avatar May 01 '15 02:05 dengemann

@haribharadwaj if you could share some minimal bad cases from the sample dataset, it would help us to tune into optimization targets. Iterating over 8000 things in Python doesn't have to be slow in principle, so we might be able to pull it off. You say you don't use preload=True, is it not an option in your case? If there were a .preload_data() you could call after instantiating your object, would it potentially fix your use case?

larsoner avatar May 01 '15 02:05 larsoner

So I do have a raw object with preload=True. If I then construct epochs = mne.Epochs(raw, preload=False) and then do epochs.get_data() or epochs.average(), either takes > 3 hours with Intel Quadcore Xeon(R) and 32 GB RAM running Ubuntu and Anaconda. Similarly if I do epochs = mne.Epochs(raw, preload=True), then this step itself takes > 3 hours..

Not sure how I could get the sample data to run into this issue. I think it it is specific to ABR type data where n_events is large. Happy to share a .fif file containing the ABR data though.

haribharadwaj avatar May 01 '15 02:05 haribharadwaj

Just make a fake event list with 8000 events.

larsoner avatar May 01 '15 02:05 larsoner

... Doesn't matter if epochs overlap

larsoner avatar May 01 '15 02:05 larsoner

Ah ok.. will cook up a gist tomorrow! Thanks, @Eric89GXL, @dengemann

haribharadwaj avatar May 01 '15 03:05 haribharadwaj

I agree > 3 hours is pretty rough, BTW. Hopefully if you use 8000 events and the same number of time points with the sample data (ABR is usually sampled at a much higher rate so you'll probably have to adjust tmin/tmax appropriately based on info['sfreq']) you'll see similar performance degradation.

For a second I wondered if the reallocations were taking a long time with get_data(), but .average() does no such reallocation so that shouldn't be the culprit. The degradation should end up be linear with the number of epochs at least for .average(), so maybe shoot for the number of events that takes 3 minutes instead of 3 hours, and hopefully it's 180/3=60 times fewer than the number of epochs you actually use, so ~130. Then we can look at it deeper. If you feel like trying to investigate, I'd suggest using line_prof / %lprun with IPython. But I'm always happy to optimize if you don't have time :)

larsoner avatar May 01 '15 03:05 larsoner

Actually... here goes:

import numpy as np

import mne
from mne import io
from mne.datasets import somato

# Load real somatosensory sample data.
data_path = somato.data_path()
raw_fname = data_path + '/MEG/somato/sef_raw_sss.fif'
n_events, tmin, tmax = 8000, -0.002, 0.015

# Setup for reading the raw data
raw = io.Raw(raw_fname, preload=True)
# Pick some single channel and match ABR sampling rate
ch_names = ['MEG 1142', ]
raw.pick_channels(ch_names)
raw.resample(sfreq=16384.)

baseline = (-0.002, 0.001)
event_samps = np.random.randint(raw.first_samp + 100, raw.last_samp - 300,
                                n_events)

# Making many event_ids to pool across (just in case it matters)
events = np.c_[event_samps, np.zeros(event_samps.shape, dtype=np.int16),
               np.random.randint(1, 100, n_events)]


epochs = mne.Epochs(raw, events, np.unique(events[:, 2]).tolist(), tmin, tmax,
                    baseline=baseline, reject=dict(grad=4000e-13),
                    preload=True, verbose='WARNING', proj=False)

Replacing the last statement with preload=False and then extracting data during averaging runs into the same issues..

epochs = mne.Epochs(raw, events, np.unique(events[:, 2]).tolist(), tmin, tmax,
                    baseline=baseline, reject=dict(grad=4000e-13),
                    preload=Flase, verbose='WARNING', proj=False)
evoked = epochs.average()

haribharadwaj avatar May 01 '15 03:05 haribharadwaj

cool, that should be good to get things started

larsoner avatar May 01 '15 03:05 larsoner

sounds like a great profiling exercise !

agramfort avatar May 01 '15 16:05 agramfort

@haribharadwaj let me know if you have time for it, otherwise I might be able to look today or Monday

larsoner avatar May 01 '15 16:05 larsoner

@Eric89GXL I won't be able to get to it before Tuesday if I did..

haribharadwaj avatar May 01 '15 16:05 haribharadwaj

I tried to make your example more minimal, but in doing so I made something that takes only 4 sec on my machine:

def test():
    # Load real somatosensory sample data.
    sfreq = 16384.
    n_events, tmin, tmax = 8000, -0.002, 0.015
    baseline = (-0.002, 0.001)

    data = np.zeros((1, int(sfreq)))
    info = mne.create_info(1, sfreq, 'eeg')
    raw = mne.io.RawArray(data, info)
    event_samps = np.random.randint(raw.first_samp + 100, raw.last_samp - 300,
                                    n_events)

    # Making many event_ids to pool across (just in case it matters)
    events = np.c_[event_samps, np.zeros(event_samps.shape, dtype=np.int32),
                   np.random.randint(1, 100, n_events)]
    epochs = mne.Epochs(raw, events, list(np.unique(events[:, 2])),
                        tmin, tmax, baseline=baseline, reject=dict(eeg=150e-6),
                        preload=False, verbose='WARNING', proj=False)
    epochs.average()


if __name__ == '__main__':
    import time
    t0 = time.time()
    test()
    print(time.time() - t0)

I'll gradually move back to the example you provided, but the speed of this one indicates that the problem is probably not in the Epochs machinery itself.

larsoner avatar May 04 '15 18:05 larsoner

Did you try running my example to see if it indeed takes long?

haribharadwaj avatar May 04 '15 18:05 haribharadwaj

Your example takes a long time, but I noticed it was hung up on the resampling. A few simple modifications of your script (to bypass the brutal resampling) is still fast for me (12 sec for 8000 epochs):

import numpy as np

import mne
from mne import io
from mne.datasets import somato


def test():
    # Load real somatosensory sample data.
    data_path = somato.data_path()
    raw_fname = data_path + '/MEG/somato/sef_raw_sss.fif'
    n_events, tmin, tmax = 8000, -0.002, 0.015

    # Setup for reading the raw data
    raw = io.Raw(raw_fname, preload=True)
    # Pick some single channel and match ABR sampling rate
    ch_names = ['MEG 1142', ]
    raw.pick_channels(ch_names)
    raw.info['sfreq'] = 16384.

    baseline = (-0.002, 0.001)
    event_samps = np.random.randint(raw.first_samp + 100, raw.last_samp - 300,
                                    n_events)

    # Making many event_ids to pool across (just in case it matters)
    events = np.c_[event_samps, np.zeros(event_samps.shape, dtype=np.int16),
                   np.random.randint(1, 100, n_events)]


    epochs = mne.Epochs(raw, events, np.unique(events[:, 2]).tolist(),
                        tmin, tmax,
                        baseline=baseline, reject=dict(grad=4000e-13),
                        preload=False, verbose='WARNING', proj=False)
    print(epochs.average().nave)


if __name__ == '__main__':
    import time
    t0 = time.time()
    test()
    print(time.time() - t0)

larsoner avatar May 04 '15 18:05 larsoner

Is it possible that you were hitting a slowdown with the use of resample in your code? If that's not it, then changing the latest example I posted so that it does have a slowdown (without adding a raw resample) should allow me to continue debugging.

larsoner avatar May 04 '15 18:05 larsoner

Ah.. yes... Your example is fast for me too... Is there anything in the EDF case that would make it slower than the FIFF case? We don't have sample EDF data, do we?

haribharadwaj avatar May 05 '15 18:05 haribharadwaj

(My ABR dataset is all BDF files)

haribharadwaj avatar May 05 '15 18:05 haribharadwaj