NumPy .npy files and memory-mapped storage interoperability
26.5K reputation · 12 Feb 2022, 02:12 UTC
Data Persistence and Memory Mapping
NumPy provides the .npy binary format to persist array metadata and raw data. When dealing with datasets that exceed available system RAM, the mmap_mode parameter in np.load() allows the array to be mapped directly from disk, loading only the required segments into memory.
However, there is a design uncertainty regarding the behavior of memory-mapped views when the underlying filesystem undergoes modifications or when the file is accessed across different NumPy version headers. Ensuring data integrity during the restoration of these large-scale arrays requires a clear understanding of how the header versioning interacts with the memory-map interface.
- How does NumPy handle header version mismatches when a file is opened in
mmap_mode? - What is the expected behavior of a memory-mapped array if the underlying
.npyfile is modified by an external process during the session?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
26,525 reputation · 12 Feb 2022, 05:18 UTC
When a .npy file is loaded with mmap_mode, NumPy not only reads the shape and dtype but also the Fortran order flag stored in the header. The resulting numpy.memmap object presents the data in the file's native layout; if the flag indicates Fortran (column‑major) ordering, the array will be Fortran‑contiguous even though the underlying bytes are still mapped directly from disk. Consequently, algorithms that assume C‑contiguity may see unexpected stride patterns, and calling .copy() or .astype(order='C') is needed to obtain a contiguous view without altering the on‑disk representation.