NumPy memmap in joblib.Parallel

This example illustrates some features enabled by using a memory map (numpy.memmap) within joblib.Parallel. First, we show that dumping a huge data array ahead of passing it to joblib.Parallel speeds up computation. Then, we show the possibility to provide write access to original data.

Speed up processing of a large data array

We create a large data array for which the average is computed for several slices.
import numpy as np

data = np.random.random((int(1e7),))
window_size = int(5e5)
slices = [slice(start, start + window_size)
          for start in range(0, data.size - window_size, int(1e5))]

The slow_mean function introduces a time.sleep() call to simulate a more expensive computation cost for which parallel computing is beneficial. Parallel may not be beneficial for very fast operation, due to extra overhead (workers creations, communication, etc.).

import time


def slow_mean(data, sl):
    """Simulate a time consuming processing."""
    time.sleep(0.01)
    return data[sl].mean()

First, we will evaluate the sequential computing on our problem.

tic = time.time()
results = [slow_mean(data, sl) for sl in slices]
toc = time.time()
print('\nElapsed time computing the average of couple of slices {:.2f} s'
      .format(toc - tic))

Out:

Elapsed time computing the average of couple of slices 1.00 s

joblib.Parallel is used to compute in parallel the average of all slices using 2 workers.

from joblib import Parallel, delayed


tic = time.time()
results = Parallel(n_jobs=2)(delayed(slow_mean)(data, sl) for sl in slices)
toc = time.time()
print('\nElapsed time computing the average of couple of slices {:.2f} s'
      .format(toc - tic))

Out:

Elapsed time computing the average of couple of slices 0.94 s

Parallel processing is already faster than the sequential processing. It is also possible to remove a bit of overhead by dumping the data array to a memmap and pass the memmap to joblib.Parallel.

import os
from joblib import dump, load

folder = './joblib_memmap'
try:
    os.mkdir(folder)
except FileExistsError:
    pass

data_filename_memmap = os.path.join(folder, 'data_memmap')
dump(data, data_filename_memmap)
data = load(data_filename_memmap, mmap_mode='r')

tic = time.time()
results = Parallel(n_jobs=2)(delayed(slow_mean)(data, sl) for sl in slices)
toc = time.time()
print('\nElapsed time computing the average of couple of slices {:.2f} s\n'
      .format(toc - tic))

Out:

Elapsed time computing the average of couple of slices 0.86 s

Therefore, dumping large data array ahead of calling joblib.Parallel can speed up the processing by removing some overhead.

Writable memmap for shared memory joblib.Parallel

slow_mean_write_output will compute the mean for some given slices as in the previous example. However, the resulting mean will be directly written on the output array.
def slow_mean_write_output(data, sl, output, idx):
    """Simulate a time consuming processing."""
    time.sleep(0.005)
    res_ = data[sl].mean()
    print("[Worker %d] Mean for slice %d is %f" % (os.getpid(), idx, res_))
    output[idx] = res_

Prepare the folder where the memmap will be dumped.

output_filename_memmap = os.path.join(folder, 'output_memmap')

Pre-allocate a writable shared memory map as a container for the results of the parallel computation.

output = np.memmap(output_filename_memmap, dtype=data.dtype,
                   shape=len(slices), mode='w+')

data is replaced by its memory mapped version. Note that the buffer has already been dumped in the previous section.

data = load(data_filename_memmap, mmap_mode='r')

Fork the worker processes to perform computation concurrently

Parallel(n_jobs=2)(delayed(slow_mean_write_output)(data, sl, output, idx)
                   for idx, sl in enumerate(slices))

Compare the results from the output buffer with the expected results

print("\nExpected means computed in the parent process:\n {}"
      .format(np.array(results)))
print("\nActual means computed by the worker processes:\n {}"
      .format(output))

Out:

Expected means computed in the parent process:
 [0.50072761 0.50024339 0.50003608 0.49994883 0.49967384 0.49962463
 0.4998147  0.4996927  0.49955404 0.49931844 0.49921372 0.49907942
 0.4996284  0.5000774  0.5005532  0.50052496 0.50088983 0.50081667
 0.50073877 0.50043482 0.50060759 0.50018122 0.49983192 0.4994801
 0.49957134 0.49980137 0.50008382 0.49997353 0.50004331 0.50027109
 0.49966879 0.49971184 0.50007261 0.49999739 0.49964602 0.49962448
 0.49933901 0.49929194 0.49954387 0.49989972 0.5005462  0.50049366
 0.50035806 0.49996584 0.50012675 0.49998574 0.50045605 0.5003024
 0.50056048 0.50011301 0.50009776 0.49993522 0.49980918 0.49973778
 0.50004384 0.49959604 0.49951694 0.50021402 0.50034432 0.50015526
 0.50061857 0.50072528 0.50024138 0.49979347 0.49975089 0.4997489
 0.49980245 0.5000838  0.50041752 0.50035736 0.49999481 0.49956664
 0.49952658 0.49947734 0.4996375  0.49991611 0.50045043 0.50046705
 0.50078556 0.50072986 0.50082585 0.50081054 0.50087443 0.50100414
 0.50065279 0.50054378 0.5003093  0.49999329 0.49966068 0.50016884
 0.49976595 0.49955463 0.49986159 0.49967939 0.49932897]

Actual means computed by the worker processes:
 [0.50072761 0.50024339 0.50003608 0.49994883 0.49967384 0.49962463
 0.4998147  0.4996927  0.49955404 0.49931844 0.49921372 0.49907942
 0.4996284  0.5000774  0.5005532  0.50052496 0.50088983 0.50081667
 0.50073877 0.50043482 0.50060759 0.50018122 0.49983192 0.4994801
 0.49957134 0.49980137 0.50008382 0.49997353 0.50004331 0.50027109
 0.49966879 0.49971184 0.50007261 0.49999739 0.49964602 0.49962448
 0.49933901 0.49929194 0.49954387 0.49989972 0.5005462  0.50049366
 0.50035806 0.49996584 0.50012675 0.49998574 0.50045605 0.5003024
 0.50056048 0.50011301 0.50009776 0.49993522 0.49980918 0.49973778
 0.50004384 0.49959604 0.49951694 0.50021402 0.50034432 0.50015526
 0.50061857 0.50072528 0.50024138 0.49979347 0.49975089 0.4997489
 0.49980245 0.5000838  0.50041752 0.50035736 0.49999481 0.49956664
 0.49952658 0.49947734 0.4996375  0.49991611 0.50045043 0.50046705
 0.50078556 0.50072986 0.50082585 0.50081054 0.50087443 0.50100414
 0.50065279 0.50054378 0.5003093  0.49999329 0.49966068 0.50016884
 0.49976595 0.49955463 0.49986159 0.49967939 0.49932897]

Clean-up the memmap

Remove the different memmap that we created. It might fail in Windows due to file permissions.
import shutil

try:
    shutil.rmtree(folder)
except:  # noqa
    print('Could not clean-up automatically.')

Total running time of the script: ( 0 minutes 4.323 seconds)

Gallery generated by Sphinx-Gallery