Skip to content

memmap loading not required data into memory #19340

Closed

Description

@JuliaSprenger

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)

Activity

  1. added
    33 - Question
    on Jun 25, 2021
  2. seberg commented on Jun 26, 2021

    @seberg
    Member

    @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 the gc may have to kick in. But even if the gc has to kick in explicitly, it will eventually and clean up map. For me adding del map before the return immediately shows the reclaim (freeing almost 100MiB).

  3. seberg commented on Jun 26, 2021

    @seberg
    Member

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

  4. JuliaSprenger commented on Jun 28, 2021

    @JuliaSprenger
    Author

    Hi @seberg, thanks for looking into this.
    I can confirm that using del map releases 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 via del map. This is is not what I would have intuitively expected from the documentation where it says Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memory and 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
    Screenshot from 2021-06-28 15-16-39_cropped
    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.

  5. seberg commented on Jun 28, 2021

    @seberg
    Member

    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.

    Is there a way to change this behaviour?

    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.

  6. JuliaSprenger commented on Jun 29, 2021

    @JuliaSprenger
    Author

    @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!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    33 - Question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions