Skip to content

Issue saving large preprocessed recording to binary file #1922

Closed

Description

@florgf88

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.

Here is the code:

ap_raw = se.read_spikeglx(folder_path=base_folder, stream_id ='imec0.ap')
ap_process = ap_raw
ap_process = spre.phase_shift(ap_process)
ap_process = spre.highpass_filter(ap_process)
ap_process = spre.common_reference(ap_process, reference='global', operator='median')

job_kwargs = dict(n_jobs=-1, chunk_duration="1s", progres_bar=True)
recording_saved = ap_process.save(folder=base_folder / "preprocessed", verbose=True, **job_kwargs)

job_kwargs = dict(delete_tmp_files= False, n_jobs=-1, chunk_duration="1s", progress_bar= True)
sorter_params = job_kwargs

sorting_KS25 = ss.run_sorter('kilosort2_5', recording_saved,
                             output_folder=base_folder / 'results_KS25',
                             verbose=True, **sorter_params)

And here a print of the output folder:
image

I appreciate any help or suggestions in how to send the data to KS. Many thanks!

Activity

  1. alejoe91 commented on Aug 21, 2023

    @alejoe91
    Member

    Hi @florgf88

    Is the progress bar printed? Can you monitor the RAM and CPU usage?

  2. added
    concurrency
    on Aug 21, 2023
  3. florgf88 commented on Aug 21, 2023

    @florgf88
    Author

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

    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!

  4. samuelgarcia commented on Aug 28, 2023

    @samuelgarcia
    Member

    Can you try the save with few jobs (4) and maybe also playing with mp_context="spawn".

  5. samuelgarcia commented on Aug 28, 2023

    @samuelgarcia
    Member

    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.

  6. florgf88 commented on Aug 30, 2023

    @florgf88
    Author

    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
    
  7. self-assigned this
    on Sep 19, 2023
  8. zm711 commented on Mar 21, 2024

    @zm711
    Member

    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.

  9. samuelgarcia commented on Mar 21, 2024

    @samuelgarcia
    Member

    thank for the feedback. So to summary with recent version of python + numpy + spikeinterface things are going better. isn't it ?

  10. zm711 commented on Mar 21, 2024

    @zm711
    Member

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

  11. h-mayorquin commented on Mar 21, 2024

    @h-mayorquin
    Contributor

    @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

  12. h-mayorquin commented on Mar 21, 2024

    @h-mayorquin
    Contributor

    @florgf88 any chance you could run this against with the latest version? Otherwise we should close this due to inactivity.

  13. florgf88 commented on Mar 21, 2024

    @florgf88
    Author

    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.

  14. zm711 commented on Mar 21, 2024

    @zm711
    Member

    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.

  15. h-mayorquin commented on Mar 21, 2024

    @h-mayorquin
    Contributor

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

  16. zm711 commented on Mar 21, 2024

    @zm711
    Member

    We are going from intan's .rhd to recording.dat. The code for that: is

    if (
    recording.binary_compatible_with(dtype="int16", time_axis=0, file_paths_lenght=1)
    and not skip_kilosort_preprocessing
    ):
    # no copy
    binary_description = recording.get_binary_description()
    binary_file_path = Path(binary_description["file_paths"][0])
    else:
    # local copy needed
    binary_file_path = sorter_output_folder / "recording.dat"
    if skip_kilosort_preprocessing:
    # 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...

    :) yep I guess so....

  17. h-mayorquin commented on Mar 21, 2024

    @h-mayorquin
    Contributor

    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.

  18. florgf88 commented on Jul 9, 2024

    @florgf88
    Author

    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
    
  19. zm711 commented on Jul 9, 2024

    @zm711
    Member

    @florgf88,

    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:

    1. add the protection line I added above if running this from a script to see if that fixes this issue (indicating a spawn problem)
    2. 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.

  20. florgf88 commented on Jul 9, 2024

    @florgf88
    Author

    Thanks a lot Zach for your help! The multiprocessing worked perfectly now :)
    I'm closing now this issue.

  21. zm711 commented on Jul 9, 2024

    @zm711
    Member

    Thanks @florgf88,

    Did (1) work for you? Just so we have that for future reference :)

  22. florgf88 commented on Jul 9, 2024

    @florgf88
    Author

    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:

    # Import packages
    import numpy as np
    from pathlib import Path
    import spikeinterface as si
    import spikeinterface.extractors as se 
    import spikeinterface.preprocessing as spre
    import spikeinterface.sorters as ss
    import spikeinterface.postprocessing as spost
    import spikeinterface.qualitymetrics as sqm
    import spikeinterface.comparison as sc
    import spikeinterface.exporters as sexp
    import spikeinterface.widgets as sw
    import warnings
    warnings.simplefilter("ignore")
    path_ks = Path(r'C:\Users\Experimenter\Desktop\Kilosort\Kilosort-2.5')
    ss.Kilosort2_5Sorter.set_kilosort2_5_path(path_ks)
    
    if __name__ == '__main__':
    	base_folder = Path(r'D:\Data\FG008_2024-05-22_g0\FG008_2024-05-22_g0_imec0') # Local folder of acquired data
    
    	ap_raw = se.read_spikeglx(folder_path=base_folder, stream_id ="imec0.ap")
    
    	ap_process = ap_raw
    	ap_process = spre.highpass_filter(ap_process)
    	ap_process = spre.phase_shift(ap_process)
    	ap_process = spre.common_reference(ap_process, reference='global', operator='median')
    
    	# Save preprocessed binary file for sorting
    	job_kwargs = dict(n_jobs=10, chunk_duration="1s", progres_bar=True)
    
    	preprocessed_output_path = base_folder / "preprocessed"
    	recording_saved = ap_process.save(folder=preprocessed_output_path, format= 'binary', overwrite=True, verbose=True, **job_kwargs)
    
  23. zm711 commented on Jul 9, 2024

    @zm711
    Member

    Awesome thanks.

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

Metadata

Metadata

Assignees

Labels

concurrency

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions