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
{{ message }}
Repository navigation
Issue saving large preprocessed recording to binary file #1922
Hello! I'm a new user of Spike Interface, currently setting a pipeline for processing Neuropixels 1.0 data. I'm experiencing an issue related to saving the preprocess recording (phase shift correction, highpass filtering and common reference applied to raw data) before running Kilosort. I didn't have a problem with a smaller dataset, but in this 2.5 hours recording, the process seems stuck: it doesn't give an error message, and the operation is not completed after several hours.
When writing to binary gets stuck, it never prints the progress bar. Here is a screenshot monitoring RAM and CPU usage:
Another thing that I noticed is that if I run the script until saving the preprocessed data, but not together with the sorter steps, it might complete the operation (not sure if this is helpful). Would it be that the PC is not powerful enough? Processor: Intel(R) Core(TM) i7-10700K CPU @ 3.80GHz 3.79 GHz, RAM 32.0 GB (31.8 GB usable).
And also as a general comment : for enormous dataset you should use a linux server remotly and not a local machine.
All the parralel processing is better on linux because the multiprocessing can use the fork which is faster.
Hi Samuel, thanks a lot for your response! And many thanks for the advice regarding using a Linux server remotely, I will consider this option.
I have tried to run my script using fewer jobs and with the mp_context ="spawn" for saving. Unfortunately, this didn't work. With jobs=1, it managed to run the full script once but took a long time to complete. I have also tried to add a line at the end of the run function in job_tools, but this didn't solve the issue. When I run the script in 2 steps: 1) using all the cores for saving to binary, and 2) running Kilosort and compressing the data using mtscomp, everything works well. Any other suggestion that I could try? Many thanks!
def run(self):
"""
Runs the defined jobs.
"""
all_chunks = divide_recording_into_chunks(self.recording, self.chunk_size)
if self.handle_returns:
returns = []
else:
returns = None
if self.n_jobs == 1:
if self.progress_bar:
all_chunks = tqdm(all_chunks, ascii=True, desc=self.job_name)
worker_ctx = self.init_func(*self.init_args)
for segment_index, frame_start, frame_stop in all_chunks:
res = self.func(segment_index, frame_start, frame_stop, worker_ctx)
if self.handle_returns:
returns.append(res)
if self.gather_func is not None:
self.gather_func(res)
else:
n_jobs = min(self.n_jobs, len(all_chunks))
######## Do you want to limit the number of threads per process?
######## It has to be done to speed up numpy a lot if multicores
######## Otherwise, np.dot will be slow. How to do that, up to you
######## This is just a suggestion, but here it adds a dependency
# parallel
with ProcessPoolExecutor(
max_workers=n_jobs,
initializer=worker_initializer,
mp_context=mp.get_context(self.mp_context),
initargs=(self.func, self.init_func, self.init_args, self.max_threads_per_process),
) as executor:
results = executor.map(function_wrapper, all_chunks)
if self.progress_bar:
results = tqdm(results, desc=self.job_name, total=len(all_chunks))
for res in results:
if self.handle_returns:
returns.append(res)
if self.gather_func is not None:
self.gather_func(res)
executor.shutdown(wait=True, cancel_futures=False) # line added by florgf88
return returns
I want to bring this back up in our minds. I was helping someone (two people actually) set up SI in our lab (a little while a go--maybe December). And we could not get the write to binary to work. We would always hang right before the progress bar appears. We then took the exact same file and brought it over to my computer and were able to get it to write the binary file no problem. I tried tuning the job_kwargs extensively on their computers (Windows 10 and Windows 11) and nothing worked. They set it aside and worked on some other parts of their project and then last week we finally just deleted the conda environment and I installed everything from source (Neo, Probeinterface, Spikeinterface) and then it worked. So not sure if we had a bug for Windows in one of the older versions, but I just fixed this last week on someone's computer by doing a full source based install for them. (Weird that I've never run into this problem despite using multiple versions), but just to provide more data about this happening.
yeah, python 3.11, numpy 1.26, and then the current dev of spikeinterface. But never figured out why it wasn't working (it's worked on mine with python 3.9,3.10, and, 3.11 + multiple numpy's and I think I started using si with 97 or 98).
@zm711
I fixed most of the errors of the binary around those versions.
There is a memory leak on np.memmap (or the way we use them in conjuntion with multiprocessing) and it was solved by creating and destroying the memmap.
Here is the PR, the tag says it was added on version 0.98. #1602
Just to clarify @h-mayorquin, they would have installed spikeinterface in around December so that would be still present in version 0.99. I know you worked a lot on fixing this and maybe updating versions worked for things, but it seems the fix for them was going from version 0.99->.101 with the associated dependency updates. (For context this was for writing a binary to be used by KS).
Thanks @florgf88, it would be great to know if updating for you fixes the issue.
Got you. I am very confused as to why this could be. The only components to write_binary is numpy's memmap and I don't think that has changed with versions or recently.
What format it was that you were trying to write? Most likely is the recording the one that did not deallocate the loaded traces.
Did you try to do non-parallel writing? To avoid any os-specific race condition.
I guess we will never know. Anyway, telling people to do a full re-install should be one of the first things that we suggest so...
# when we skip the kilosort preprocessing we need to extend the file with zero pad to ensure
# that the number of sample is compatible with batch size (NT)
nt=params["NT"]
num_samples=recording.get_num_samples()
pad=nt-num_samples%nt
padding_start=0
padding_end=pad
padded_recording=TracePaddedRecording(
parent_recording=recording,
padding_start=padding_start,
padding_end=padding_end,
)
else:
padded_recording=recording
write_binary_recording(
recording=padded_recording,
file_paths=[binary_file_path],
dtype="int16",
**get_job_kwargs(params, verbose),
)
this should then just write the binary recording. We tried it once (n_jobs=1), it was a 40gb file so it was being done over night and my labmate was too inpatient when she got back to work and so just canceled so we never saw if it finished or not. Like I said it has always worked on my computer which is weird (one of my labmates has the exact same model of computer as me).
So I agree I don't think we will ever know....
Anyway, telling people to do a full re-install should be one of the first things that we suggest so...
Yeah, hard to venture guessess other than the memmaps of intan not getting released. On Windows the commited memory might act weird. Would have needed to be there.
Hello! I now had the possibility to retest and follow up on this. I tried the same code I posted initially (now using spike Interface version 0.100.8 in Windows 11 on a more powerful PC than before), and I'm still having issues with saving the preprocessed recording before running Kilosort; however, now I'm receiving the following error. Any help in solving this would be very appreciated, thanks!
write_binary_recording with n_jobs = 10 and chunk_size = 30000
Setting KILOSORT2_5_PATH environment variable for subprocess calls to: C:\Users\Experimenter\Desktop\Kilosort\Kilosort-2.5
write_binary_recording with n_jobs = 10 and chunk_size = 30000
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\spawn.py", line 131, in _main
prepare(preparation_data)
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\spawn.py", line 246, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\spawn.py", line 297, in _fixup_main_from_path
main_content = runpy.run_path(main_path,
^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen runpy>", line 291, in run_path
File "<frozen runpy>", line 98, in _run_module_code
File "<frozen runpy>", line 88, in _run_code
File "C:\Software\Ephys-scripts\ephys_aquisition\SpikeInterface\pipeline_ephys_preprocessing_last.py", line 41, in <module>
recording_saved = ap_process.save(folder=preprocessed_output_path, format= 'binary', overwrite=True, verbose=True, **job_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\site-packages\spikeinterface\core\base.py", line 845, in save
loaded_extractor = self.save_to_folder(**kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\site-packages\spikeinterface\core\base.py", line 931, in save_to_folder
cached = self._save(folder=folder, verbose=verbose, **save_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\site-packages\spikeinterface\core\baserecording.py", line 465, in _save
write_binary_recording(self, file_paths=file_paths, dtype=dtype, **job_kwargs)
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\site-packages\spikeinterface\core\recording_tools.py", line 137, in write_binary_recording
executor.run()
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\site-packages\spikeinterface\core\job_tools.py", line 408, in run
results = executor.map(function_wrapper, all_chunks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\concurrent\futures\process.py", line 837, in map
results = super().map(partial(_process_chunk, fn),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\concurrent\futures\_base.py", line 608, in map
fs = [self.submit(fn, *args) for args in zip(*iterables)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\concurrent\futures\_base.py", line 608, in <listcomp>
fs = [self.submit(fn, *args) for args in zip(*iterables)]
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\concurrent\futures\process.py", line 808, in submit
self._adjust_process_count()
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\concurrent\futures\process.py", line 767, in _adjust_process_count
self._spawn_process()
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\concurrent\futures\process.py", line 785, in _spawn_process
p.start()
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\context.py", line 336, in _Popen
return Popen(process_obj)
^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
prep_data = spawn.get_preparation_data(process_obj._name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\spawn.py", line 164, in get_preparation_data
_check_not_importing_main()
File "C:\Users\experimenter\anaconda3\envs\si_env\Lib\multiprocessing\spawn.py", line 140, in _check_not_importing_main
raise RuntimeError('''
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
To fix this issue, refer to the "Safe importing of main module"
section in https://docs.python.org/3/library/multiprocessing.html
you're on a windows computer which sometimes needs protection using the
if __name__ == '__main__':
write_binary(xx)
As the error is trying to get at. For multiprocessing on mac and windows they use spawn which can lead to those errors. You could test two things:
add the protection line I added above if running this from a script to see if that fixes this issue (indicating a spawn problem)
switch n_jobs to 1 which will shut off multiprocessing (general multiprocessing problem).
I would try them in this order since if (1) works you will still be able to make use of the multiprocessing. You may be getting this through the run_sorter function so you could either protect the run_sorter or you could prewrite the binary and then feed the binary path to the sorter instead in which case you would just protect writing the binary.
Activity
alejoe91 commentedon Aug 21, 2023
Hi @florgf88
Is the progress bar printed? Can you monitor the RAM and CPU usage?
florgf88 commentedon Aug 21, 2023
Hi @alejoe91, thanks for your replay!
When writing to binary gets stuck, it never prints the progress bar. Here is a screenshot monitoring RAM and CPU usage:

Another thing that I noticed is that if I run the script until saving the preprocessed data, but not together with the sorter steps, it might complete the operation (not sure if this is helpful). Would it be that the PC is not powerful enough? Processor: Intel(R) Core(TM) i7-10700K CPU @ 3.80GHz 3.79 GHz, RAM 32.0 GB (31.8 GB usable).
Many thanks!
samuelgarcia commentedon Aug 28, 2023
Can you try the save with few jobs (4) and maybe also playing with mp_context="spawn".
samuelgarcia commentedon Aug 28, 2023
And also as a general comment : for enormous dataset you should use a linux server remotly and not a local machine.
All the parralel processing is better on linux because the multiprocessing can use the fork which is faster.
florgf88 commentedon Aug 30, 2023
Hi Samuel, thanks a lot for your response! And many thanks for the advice regarding using a Linux server remotely, I will consider this option.
I have tried to run my script using fewer jobs and with the mp_context ="spawn" for saving. Unfortunately, this didn't work. With jobs=1, it managed to run the full script once but took a long time to complete. I have also tried to add a line at the end of the run function in job_tools, but this didn't solve the issue. When I run the script in 2 steps: 1) using all the cores for saving to binary, and 2) running Kilosort and compressing the data using mtscomp, everything works well. Any other suggestion that I could try? Many thanks!
zm711 commentedon Mar 21, 2024
I want to bring this back up in our minds. I was helping someone (two people actually) set up SI in our lab (a little while a go--maybe December). And we could not get the write to binary to work. We would always hang right before the progress bar appears. We then took the exact same file and brought it over to my computer and were able to get it to write the binary file no problem. I tried tuning the
job_kwargsextensively on their computers (Windows 10 and Windows 11) and nothing worked. They set it aside and worked on some other parts of their project and then last week we finally just deleted the conda environment and I installed everything from source (Neo, Probeinterface, Spikeinterface) and then it worked. So not sure if we had a bug for Windows in one of the older versions, but I just fixed this last week on someone's computer by doing a full source based install for them. (Weird that I've never run into this problem despite using multiple versions), but just to provide more data about this happening.samuelgarcia commentedon Mar 21, 2024
thank for the feedback. So to summary with recent version of python + numpy + spikeinterface things are going better. isn't it ?
zm711 commentedon Mar 21, 2024
yeah, python 3.11, numpy 1.26, and then the current dev of spikeinterface. But never figured out why it wasn't working (it's worked on mine with python 3.9,3.10, and, 3.11 + multiple numpy's and I think I started using si with 97 or 98).
h-mayorquin commentedon Mar 21, 2024
@zm711
I fixed most of the errors of the binary around those versions.
There is a memory leak on
np.memmap(or the way we use them in conjuntion with multiprocessing) and it was solved by creating and destroying the memmap.Here is the PR, the tag says it was added on version 0.98.
#1602
h-mayorquin commentedon Mar 21, 2024
@florgf88 any chance you could run this against with the latest version? Otherwise we should close this due to inactivity.
florgf88 commentedon Mar 21, 2024
Many thanks for bringing this up!
@h-mayorquin I found another solution at that time without SI, but I will try again and let you know the outcome.
zm711 commentedon Mar 21, 2024
Just to clarify @h-mayorquin, they would have installed spikeinterface in around December so that would be still present in version 0.99. I know you worked a lot on fixing this and maybe updating versions worked for things, but it seems the fix for them was going from version 0.99->.101 with the associated dependency updates. (For context this was for writing a binary to be used by KS).
Thanks @florgf88, it would be great to know if updating for you fixes the issue.
h-mayorquin commentedon Mar 21, 2024
Got you. I am very confused as to why this could be. The only components to write_binary is numpy's memmap and I don't think that has changed with versions or recently.
What format it was that you were trying to write? Most likely is the recording the one that did not deallocate the loaded traces.
Did you try to do non-parallel writing? To avoid any os-specific race condition.
I guess we will never know. Anyway, telling people to do a full re-install should be one of the first things that we suggest so...
zm711 commentedon Mar 21, 2024
We are going from intan's
.rhdtorecording.dat. The code for that: isspikeinterface/src/spikeinterface/sorters/external/kilosortbase.py
Lines 129 to 160 in 52617ee
this should then just write the binary recording. We tried it once (n_jobs=1), it was a 40gb file so it was being done over night and my labmate was too inpatient when she got back to work and so just canceled so we never saw if it finished or not. Like I said it has always worked on my computer which is weird (one of my labmates has the exact same model of computer as me).
So I agree I don't think we will ever know....
:) yep I guess so....
h-mayorquin commentedon Mar 21, 2024
Yeah, hard to venture guessess other than the memmaps of intan not getting released. On Windows the commited memory might act weird. Would have needed to be there.
florgf88 commentedon Jul 9, 2024
Hello! I now had the possibility to retest and follow up on this. I tried the same code I posted initially (now using spike Interface version 0.100.8 in Windows 11 on a more powerful PC than before), and I'm still having issues with saving the preprocessed recording before running Kilosort; however, now I'm receiving the following error. Any help in solving this would be very appreciated, thanks!
zm711 commentedon Jul 9, 2024
@florgf88,
you're on a windows computer which sometimes needs protection using the
As the error is trying to get at. For multiprocessing on mac and windows they use spawn which can lead to those errors. You could test two things:
I would try them in this order since if (1) works you will still be able to make use of the multiprocessing. You may be getting this through the
run_sorterfunction so you could either protect the run_sorter or you could prewrite the binary and then feed the binary path to the sorter instead in which case you would just protect writing the binary.florgf88 commentedon Jul 9, 2024
Thanks a lot Zach for your help! The multiprocessing worked perfectly now :)
I'm closing now this issue.
zm711 commentedon Jul 9, 2024
Thanks @florgf88,
Did (1) work for you? Just so we have that for future reference :)
florgf88 commentedon Jul 9, 2024
Yes, option 1 indeed. I ran this from a script. I'm pasting the updated version here in case it is helpful to anyone else:
zm711 commentedon Jul 9, 2024
Awesome thanks.