From 0060cb563b28a828090fa5bb2b5022f157385e7d Mon Sep 17 00:00:00 2001 From: Alessio Buccino Date: Mon, 30 Nov 2026 17:22:15 +0100 Subject: [PATCH] feat: add cache option to binaryrecording to avoid memmap cache --- src/spikeinterface/core/baserecording.py | 3 ++ src/spikeinterface/core/binaryfolder.py | 12 +++-- .../core/binaryrecordingextractor.py | 51 +++++++++++++++++++ .../tests/test_binaryrecordingextractor.py | 47 +++++++++++++++++ 4 files changed, 109 insertions(+), 4 deletions(-) diff --git a/src/spikeinterface/core/baserecording.py b/src/spikeinterface/core/baserecording.py index 76167ea792..cf75a66fde 100644 --- a/src/spikeinterface/core/baserecording.py +++ b/src/spikeinterface/core/baserecording.py @@ -852,6 +852,9 @@ def save(self, format="binary", verbose: bool = False, **save_kwargs): - dtype : str, optional The data type to use for saving the recording. If not provided, the recording's dtype will be used. + - cache : bool, default: True + Passed to the returned `BinaryFolderRecording`. If False, its traces are read without + keeping them in the OS page cache (see `BinaryRecordingExtractor`). * "zarr" format: - folder : str or Path The folder where the Zarr files will be saved. diff --git a/src/spikeinterface/core/binaryfolder.py b/src/spikeinterface/core/binaryfolder.py index 65fe6e153b..4077399c06 100644 --- a/src/spikeinterface/core/binaryfolder.py +++ b/src/spikeinterface/core/binaryfolder.py @@ -30,6 +30,9 @@ class BinaryFolderRecording(BinaryRecordingExtractor): Parameters ---------- folder_path : str or Path + cache : bool, default: True + If False, traces are read without keeping them in the OS page cache. + See `BinaryRecordingExtractor` for details. Returns ------- @@ -37,7 +40,7 @@ class BinaryFolderRecording(BinaryRecordingExtractor): The recording """ - def __init__(self, folder_path): + def __init__(self, folder_path, cache: bool = True): folder_path = Path(folder_path) with open(folder_path / "binary.json", "r") as f: @@ -50,7 +53,7 @@ def __init__(self, folder_path): d = make_paths_absolute(d, folder_path) - BinaryRecordingExtractor.__init__(self, **d["kwargs"]) + BinaryRecordingExtractor.__init__(self, **{**d["kwargs"], "cache": cache}) # Load properties load_properties_from_folder(folder_path / "properties", self) @@ -97,7 +100,7 @@ def __init__(self, folder_path): if time_file.is_file(): rs._time_vector = np.load(time_file, mmap_mode="r") - self._kwargs = dict(folder_path=str(Path(folder_path).absolute())) + self._kwargs = dict(folder_path=str(Path(folder_path).absolute()), cache=cache) self._bin_kwargs = d["kwargs"] if "num_channels" not in self._bin_kwargs: assert "num_chan" in self._bin_kwargs, "Cannot find num_channels or num_chan in binary.json" @@ -123,6 +126,7 @@ def write_recording( verbose: bool = False, overwrite: bool = False, dtype=None, + cache: bool = True, **job_kwargs, ): from .time_series_tools import write_binary @@ -189,7 +193,7 @@ def write_recording( # Create the si_folder file to make the load() easier until version 0.105.0 # All properties, annotations, and probe information are already saved in the folder, # so we don't need to include them in the si_folder.json - cached = BinaryFolderRecording(folder_path=folder_path) + cached = BinaryFolderRecording(folder_path=folder_path, cache=cache) si_folder_path = folder_path / "si_folder.json" cached.dump_to_json( file_path=si_folder_path, diff --git a/src/spikeinterface/core/binaryrecordingextractor.py b/src/spikeinterface/core/binaryrecordingextractor.py index cdbf722e90..71d49a6ec0 100644 --- a/src/spikeinterface/core/binaryrecordingextractor.py +++ b/src/spikeinterface/core/binaryrecordingextractor.py @@ -1,4 +1,6 @@ import mmap +import os +import threading import warnings from pathlib import Path @@ -42,6 +44,13 @@ class BinaryRecordingExtractor(BaseRecording): file_timestamps_paths : str or Path or list, default: None Path to the binary file containing timestamps for each segment. If None, timestamps are not loaded. In a list, an entry is None for a segment without timestamps. + cache : bool, default: True + If True, traces are read through a memory map and stay in the OS page cache, which makes repeated + reads of the same data fast. If False, traces are copied into memory with a plain read and dropped + from the page cache right after (``posix_fadvise(POSIX_FADV_DONTNEED)``, where available). Use False for + recordings larger than the available memory that are read in several full passes (e.g. by spike sorters): + their pages would otherwise fill the page cache, which can stall reading under a container + memory limit. Notes ----- @@ -67,6 +76,7 @@ def __init__( offset_to_uV: float | np.ndarray | None = None, is_filtered: bool | None = None, file_timestamps_paths: str | Path | list[str | Path | None] | None = None, + cache: bool = True, ): if channel_ids is None: @@ -114,6 +124,7 @@ def __init__( time_axis, file_offset, file_timestamps_path, + cache=cache, ) self.add_recording_segment(rec_segment) @@ -143,6 +154,7 @@ def __init__( if file_timestamps_paths is not None else None ), + "cache": cache, } @classmethod @@ -201,6 +213,7 @@ def __init__( time_axis, file_offset, file_timestamps_path=None, + cache=True, ): BaseRecordingSegment.__init__(self, sampling_frequency=sampling_frequency, t_start=t_start) self.num_channels = num_channels @@ -209,6 +222,9 @@ def __init__( self.time_axis = time_axis self.file_path = file_path self.file = open(self.file_path, "rb") + self.cache = cache + # without os.preadv (Windows), reads share the file position: serialize seek + read + self._read_lock = threading.Lock() self.bytes_per_sample = self.num_channels * self.dtype.itemsize self.data_size_in_bytes = Path(file_path).stat().st_size - file_offset self.num_samples = self.data_size_in_bytes // self.bytes_per_sample @@ -230,6 +246,8 @@ def get_traces( end_frame: int | None = None, channel_indices: list | None = None, ) -> np.ndarray: + if not self.cache: + return self._get_traces_uncached(start_frame, end_frame, channel_indices) # Calculate byte offsets for start and end frames start_byte = self.file_offset + start_frame * self.bytes_per_sample @@ -272,6 +290,39 @@ def get_traces( return traces + def _get_traces_uncached(self, start_frame, end_frame, channel_indices): + num_frames = end_frame - start_frame + traces = np.empty(num_frames * self.num_channels, dtype=self.dtype) + buffer = memoryview(traces).cast("B") + start_byte = self.file_offset + start_frame * self.bytes_per_sample + fd = self.file.fileno() + + num_read = 0 + while num_read < buffer.nbytes: # a single read can return fewer bytes than requested + if hasattr(os, "preadv"): + n = os.preadv(fd, [buffer[num_read:]], start_byte + num_read) + else: + with self._read_lock: + self.file.seek(start_byte + num_read) + n = self.file.readinto(buffer[num_read:]) + if not n: + raise EOFError(f"Unexpected end of file {self.file_path} at byte {start_byte + num_read}") + num_read += n + + if hasattr(os, "posix_fadvise"): + # drop the pages just read from the page cache + os.posix_fadvise(fd, start_byte, buffer.nbytes, os.POSIX_FADV_DONTNEED) + + if self.time_axis == 0: + traces = traces.reshape(num_frames, self.num_channels) + else: + traces = traces.reshape(self.num_channels, num_frames).T + + if channel_indices is not None: + traces = traces[:, channel_indices] + + return traces + def __del__(self): # Ensure that the file handle is closed when the segment is garbage-collected try: diff --git a/src/spikeinterface/core/tests/test_binaryrecordingextractor.py b/src/spikeinterface/core/tests/test_binaryrecordingextractor.py index 869b4a34da..72106e4c2a 100644 --- a/src/spikeinterface/core/tests/test_binaryrecordingextractor.py +++ b/src/spikeinterface/core/tests/test_binaryrecordingextractor.py @@ -152,3 +152,50 @@ def test_num_chan_backward_compatibility_within_same_version(tmp_path): if __name__ == "__main__": test_BinaryRecordingExtractor() + + +@pytest.mark.parametrize("time_axis", [0, 1]) +def test_cache_false_matches_cache_true(tmp_path, time_axis): + num_channels = 5 + num_samples = 3001 + file_offset = 13 + dtype = "int16" + data = np.random.default_rng(0).integers(-1000, 1000, size=(num_samples, num_channels), dtype=dtype) + file_path = tmp_path / "traces.raw" + with open(file_path, "wb") as f: + f.write(b"\0" * file_offset) + f.write((data if time_axis == 0 else data.T.copy()).tobytes()) + + kwargs = dict( + file_paths=file_path, + sampling_frequency=30_000.0, + num_channels=num_channels, + dtype=dtype, + time_axis=time_axis, + file_offset=file_offset, + ) + rec_cached = BinaryRecordingExtractor(**kwargs) + rec_uncached = BinaryRecordingExtractor(**kwargs, cache=False) + assert rec_uncached._kwargs["cache"] is False + + channel_ids = rec_cached.channel_ids[[0, 2, 4]] + for start_frame, end_frame, ids in [ + (None, None, None), + (5, 2049, None), + (2000, num_samples, channel_ids), + ]: + expected = rec_cached.get_traces(start_frame=start_frame, end_frame=end_frame, channel_ids=ids) + traces = rec_uncached.get_traces(start_frame=start_frame, end_frame=end_frame, channel_ids=ids) + np.testing.assert_array_equal(traces, expected) + np.testing.assert_array_equal(rec_uncached.get_traces(), data) + + # the flag survives a dump/load round trip + rec_loaded = BaseExtractor.from_dict(rec_uncached.to_dict()) + assert rec_loaded._recording_segments[0].cache is False + + +def test_save_binary_cache_false(tmp_path): + recording = MockRecording(num_channels=4, sampling_frequency=10_000.0, durations=[0.5]) + saved = recording.save(folder=tmp_path / "binary", cache=False) + assert saved._recording_segments[0].cache is False + np.testing.assert_array_equal(saved.get_traces(), recording.get_traces())