-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Persistent managed memmap caches + preload="memmap" sentinel #14216
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+376
−26
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
84aae35
Add portable persistent Raw preload cache
bruAristimunha 53a65f9
Simplify portable Raw preload cache locking
bruAristimunha ade3eb3
[autofix.ci] apply automated fixes
autofix-ci[bot] b35640a
Simplify Raw preload cache identity and tests
bruAristimunha a138fb7
Simplify persistent Raw preload caching
bruAristimunha 8e0a247
perf: keep the Raw preload cache lock-free and lift the "auto" sentinel
bruAristimunha 661a09d
Merge branch 'main' into pr/5-memmap-cache
bruAristimunha bf5a3d0
Test preload="auto" in _test_raw_reader across formats
bruAristimunha 3a28327
Cover FIL in _test_raw_reader
bruAristimunha b282e6d
Apply projectors in the ANT reader
bruAristimunha File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Fix bug where :func:`mne.io.read_raw_ant` and :func:`mne.io.read_raw_curry` ignored projections and non-boolean ``preload`` values respectively when reading data lazily, by `Bruno Aristimunha`_. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Speed up repeated preloading of any file-backed :class:`~mne.io.Raw` with ``preload="auto"``, which persists decoded data in a copy-on-write cache below :func:`mne.set_cache_dir`, by `Bruno Aristimunha`_. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| """Persistent decoded-data cache for Raw readers.""" | ||
|
|
||
| # Authors: The MNE-Python contributors. | ||
| # License: BSD-3-Clause | ||
| # Copyright the MNE-Python contributors. | ||
|
|
||
| import hashlib | ||
| import os | ||
| import pickle | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
|
|
||
| from .. import __version__ as MNE_VERSION # ty: ignore[unresolved-import] | ||
| from ..utils import get_config, logger | ||
|
|
||
| _RAW_PRELOAD_CACHE_VERSION = 1 | ||
|
|
||
|
|
||
| def _raw_preload_cache_info(raw): | ||
| """Return the cache path and decoded array description.""" | ||
| cache_root = get_config("MNE_CACHE_DIR", None) | ||
| if cache_root is None: | ||
| raise ValueError( | ||
| 'preload="auto" requires a configured cache directory; use ' | ||
| "mne.set_cache_dir(...) first" | ||
| ) | ||
| cache_dir = Path(cache_root).expanduser().resolve() | ||
| cache_dir = cache_dir / f"raw-preload-v{_RAW_PRELOAD_CACHE_VERSION}" | ||
| cache_dir.mkdir(mode=0o700, parents=True, exist_ok=True) | ||
|
|
||
| sources = [] | ||
| for filename in raw.filenames: | ||
| if filename is None: | ||
| raise ValueError( | ||
| 'preload="auto" requires stable source files; use preload=True ' | ||
| "or an explicit memory-map path" | ||
| ) | ||
| path = Path(filename).resolve(strict=True) | ||
| # some formats (e.g., CTF) name a directory rather than a single file | ||
| members = sorted(path.rglob("*")) if path.is_dir() else [path] | ||
| for member in members: | ||
| if not member.is_file(): | ||
| continue | ||
| result = member.stat() | ||
| sources.append((str(member), int(result.st_size), int(result.st_mtime_ns))) | ||
|
|
||
| dtype = np.dtype(raw._dtype) | ||
| shape = (int(raw.info["nchan"]), int(raw.n_times)) | ||
| identity = ( | ||
| _RAW_PRELOAD_CACHE_VERSION, | ||
| MNE_VERSION, | ||
| type(raw).__module__, | ||
| type(raw).__qualname__, | ||
| sources, | ||
| raw._raw_extras, | ||
| raw._cals, | ||
| dtype.str, | ||
| shape, | ||
| ) | ||
| try: | ||
| key = hashlib.sha256(pickle.dumps(identity, protocol=5)).hexdigest() | ||
| except Exception as exc: | ||
| raise ValueError( | ||
| f'preload="auto" cannot identify this {type(raw).__name__} source' | ||
| ) from exc | ||
| return cache_dir / f"{key}.data", sources, shape, dtype | ||
|
|
||
|
|
||
| def _raw_preload_cache_read(path, shape, dtype): | ||
| """Map a complete decoded-data cache entry.""" | ||
| try: | ||
| nbytes = int(np.prod(shape, dtype=np.int64)) * dtype.itemsize | ||
| if path.stat().st_size != nbytes: | ||
| return None | ||
| return np.memmap(path, mode="c", dtype=dtype, shape=shape) | ||
| except OSError: | ||
| return None | ||
|
|
||
|
|
||
| def _raw_preload_auto(raw): | ||
| """Reuse or create an automatic decoded-data cache entry.""" | ||
| path, sources, shape, dtype = _raw_preload_cache_info(raw) | ||
| data = _raw_preload_cache_read(path, shape, dtype) | ||
| if data is not None: | ||
| logger.info(f"Reusing decoded data from {path}") | ||
| return data | ||
|
|
||
| # The temporary is per-process and os.replace is atomic, so concurrent | ||
| # misses need no lock; they at worst decode the same entry twice. | ||
| logger.info(f"Creating decoded data cache in {path.parent}") | ||
| temporary = path.with_suffix(f".{os.getpid()}.tmp") | ||
| try: | ||
| data = np.memmap(temporary, mode="w+", dtype=dtype, shape=shape) | ||
| try: | ||
| raw._read_segment(data_buffer=data) | ||
| data.flush() | ||
| finally: | ||
| data._mmap.close() # ty: ignore[unresolved-attribute] | ||
| if _raw_preload_cache_info(raw)[1] != sources: | ||
| raise RuntimeError( | ||
| "Source data changed while decoded cache was created; retry" | ||
| ) | ||
| try: | ||
| os.replace(temporary, path) | ||
| except OSError: | ||
| # Windows refuses to replace an entry another process already mapped. | ||
| pass | ||
| finally: | ||
| temporary.unlink(missing_ok=True) | ||
| data = _raw_preload_cache_read(path, shape, dtype) | ||
| if data is None: | ||
| raise RuntimeError(f"Could not read back the decoded data cache at {path}") | ||
| return data | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.