Repository navigation
Closed
Labels
33 - QuestionQuestion about NumPy usage or development
Description
When loading only very few, equally spaced bytes of a large binary file via a memory map the consumed memory does not correspond to the data accessed, but almost the complete content of the file is is loaded.
This seems not to be an issue of an underlying caching mechanism on OS level as when loading the equally spaced bytes via a filehandler read, this phenomenon does not occur.
Reproducing code example:
from memory_profiler import profile
import os
import copy
import numpy as np
filename = 'output_file'
# generate a 100MB binary test file
with open(filename, 'wb') as fout:
fout.write(os.urandom(int(1024*1000*100)))
@profile
def read_with_memmap(filename):
map = np.memmap(filename, dtype=[('sample', 'B', 1000)], offset=0, mode='r')
# deepcopying data to force a load into memory
selected_data = copy.deepcopy(map['sample'][:,0])
return selected_data
@profile
def read_bytes_directly(filename):
# utility function to read first byte of regularly spaced data packets
def get_first_packet_byte(packet_id, file_handler, packet_size):
file_handler.seek(packet_size * packet_id, 0)
return file_handler.read(1)
# vectorize packet access for faster execution
vec_get_first_packet_byte = np.vectorize(get_first_packet_byte)
packet_ids = np.arange(1024*100)
with open(filename, 'rb') as fin:
selected_data = vec_get_first_packet_byte(packet_ids, fin, 1000)
return selected_data
data_mapped = read_with_memmap(filename)
data_direct = read_bytes_directly(filename).view(dtype='uint8')
# check that read data are identical
assert (data_direct == data_mapped).all()Output:
Line # Mem usage Increment Occurences Line Contents
============================================================
13 32.8 MiB 32.8 MiB 1 @profile
14 def read_with_memmap(filename):
15 33.0 MiB 0.2 MiB 1 map = np.memmap(filename, dtype=[('sample', 'B', 1000)], offset=0, mode='r')
16 # deepcopying data to force a load into memory
17 130.1 MiB 97.1 MiB 1 selected_data = copy.deepcopy(map['sample'][:,0])
18 130.1 MiB 0.0 MiB 1 return selected_data
Line # Mem usage Increment Occurences Line Contents
============================================================
20 33.2 MiB 33.2 MiB 1 @profile()
21 def read_bytes_directly(filename):
22
23 # utility function to read first byte of regularly spaced data packets
24 39.6 MiB 5.1 MiB 102402 def get_first_packet_byte(packet_id, file_handler, packet_size):
25 39.6 MiB 0.0 MiB 102401 file_handler.seek(packet_size * packet_id, 0)
26 39.6 MiB 0.5 MiB 102401 return file_handler.read(1)
27
28 # vectorize packet access for faster execution
29 33.2 MiB 0.0 MiB 1 vec_get_first_packet_byte = np.vectorize(get_first_packet_byte)
30
31 33.9 MiB 0.8 MiB 1 packet_ids = np.arange(1024*100)
32 33.9 MiB 0.0 MiB 1 with open(filename, 'rb') as fin:
33 34.4 MiB -5.2 MiB 1 selected_data = vec_get_first_packet_byte(packet_ids, fin, 1000)
34 34.4 MiB 0.0 MiB 1 return selected_data
In line 17 almost the complete 100MB of the test file are loaded into memory, whereas in the alternative implementation accessing the same data using filehandler.read() only 500kb are used (see line 26).
NumPy/Python version information:
Numpy version: 1.20.3; Sys version: 3.7.10 (default, Feb 26 2021, 18:47:35)
and
Numpy version: 1.19.2; Sys version: 3.8.5 (default, Sep 4 2020, 07:30:14)
Metadata
Metadata
Assignees
Labels
33 - QuestionQuestion about NumPy usage or development
Activity
seberg commentedon Jun 26, 2021
@JuliaSprenger two things, first I am not sure how the data is reported. This is memory mapped, so the data probably is reported, but nothing else is done by the CPU (it doesn't actually load it into RAM).
Second, typically the OS will not reclaim memory, which is may be reported incorrectly in things like
memory_profiler(I am not sure if it works on the OS or Python level). So sometimes a process looks like it uses a lot of memory, but that memory is available for re-use.In this case, all you are missing is the
del map, that implicitly happens eventually. It might be that memory-profiler doesn't notice because thegcmay have to kick in. But even if thegchas to kick in explicitly, it will eventually and clean upmap. For me addingdel mapbefore the return immediately shows the reclaim (freeing almost 100MiB).seberg commentedon Jun 26, 2021
I guess one thing may be that reading every 1000-bytes. That means that you are probably touching every single page so you do "touch" all of the data in
mapin a sense. To be honest, I do not know what the OS does exactly when you read just a few bytes from a memory-map, it may be that the page-fault pulls in everything from that page. Memory usage wise, I do not think you should worry. But, it may be that using a memory-map to just read a few bytes is relatively slow (I really do not know).JuliaSprenger commentedon Jun 28, 2021
Hi @seberg, thanks for looking into this.
I can confirm that using
del mapreleases the memory again, so this is a good solution for medium sized files. Here the file can be almost completely loaded into memory, relevant data sliced & copied and then the major part of the memory released viadel map. This is is not what I would have intuitively expected from the documentation where it saysMemory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memoryand also did not see any hint towards this behavior in other parts of the documentation. I think adding a note for this kind of behavior could prevent many other users from having similar issues.Regarding the reusability of the memory: I don't think that the memory is only seemingly allocated and can be in principle released in the process to be re-used again. I did a test with the filesize in the order of the available RAM and my system started swapping instead of releasing and reusing memory

Is there a way to change this behaviour? To be honest I am not experienced with memory pages, is there maybe a way to configure the the minimal memory unit to be loaded by a memmap? Then this could be configured to match the size of the data chunks loaded.
seberg commentedon Jun 28, 2021
Not sure how the OS decides to swap, but it is probably just guessing that your memormap will be used again, while whatever is swapped is not? Since swapping out would be terrible for performance if you re-use those pages (and you just used them, so that is not a bad guess). So, I guess it might be OK or not depending on the use-case.
Memory pages have a fixed size, usually 512kiB or 2MiB, IIRC. You might be able to decide which one of those you are getting (disabling "hugepages" to get the smaller one) on linux at least, but its specific to the computer if you can.
There are a few other hints for memory-maps and generally memory allocations that might change behaviour, but I don't know, and somewhat doubt it will make big differences.
If all you need is really a single, sparse pass over the file – maybe even unbuffered since you don't want to read-ahead at all – I would guess that memory-maps are just not a fast way to do that.
Anyway, I am at the end of my knowledge, but maybe you get lucky and someone else has a tip of what to use. My best idea is to just use low-level file access in cython/C or so if it matters a lot.
JuliaSprenger commentedon Jun 29, 2021
@seberg Thanks for these insights. I thought that actually the swapped data might be the mapped data, as swapping started when reading from the memory map, but maybe your are right and other parts of the data in memory are being swapped out instead.
For now explicitly deleting the memory map after data extraction solves my problem. Thanks for your help!