Skip to content
Snippets Groups Projects
Commit c2854eb3 authored by manifest-rules's avatar manifest-rules
Browse files

New notebook on third-party parallelisation libs (WIP)

parent 8a659bab
No related branches found
No related tags found
1 merge request!38Add practical which introduces some third-party parallelisation libraries
%% Cell type:markdown id:65545a03 tags:
# Parallel processing in Python
While Python has built-in support for threading and parallelising in the
[`threading`](https://docs.python.org/3/library/threading.html) and
[`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html)
modules, there are a range of third-party libraries which you can use to improve the performance of your code.
Contents:
* [JobLib](#joblib)
* [Dask](#dask)
* [Dask Numpy API](#dask-numpy-api)
* [Low-level Dask API](#low-level-dask-api)
* [Distributing computation with Dask](#distributing-computation-with-dask)
* [fsl-pipe](#fsl-pipe)
<a class="anchor" id="joblib"></a>
# JobLib
https://joblib.readthedocs.io/en/stable/
JobLib has been around for a while, and is a simple and lightweight library with two main features:
- An API for "embarrassingly parallel" tasks.
- An API for caching/re-using the results of time-consuming computations.
On the surface, JobLib does not provide any functionality that cannot already be accomplished with built-in libraries such as `multiprocessing` and `functools`. However, the JobLib developers have put a lot of effort into ensuring that JobLib:
- is easy to use,
- works consistently across all of the major platforms, and
- works as efficiently as possible with Numpy arrays
We can use the JobLib API by importing the `joblib` package (we'll also use `numpy` and `time` in this example):
%% Cell type:code id:5c8c5a11 tags:
```
import numpy as np
import joblib
import time
```
%% Cell type:markdown id:5b128829 tags:
Now, let's say that we have a collection of `numpy` arrays containing image data for a group of subjects:
%% Cell type:code id:8727c53a tags:
```
datasets = [np.random.random((91, 109, 91)) for i in range(10)]
```
%% Cell type:markdown id:211fb083 tags:
And we want to calculate some metric on each image. We simply need to define a function which contains the calculation we want to perform (the `time.sleep` call is there just to simulate a complex calculation):
%% Cell type:code id:bcd89418 tags:
```
def do_calculation(input_data):
time.sleep(2)
return input_data.mean()
```
%% Cell type:markdown id:4a499b91 tags:
We can now use `joblib.Parallel` and `joblib.delayed` to parallelise those calculations. `joblib.Parallel` sets up a pool of worker processes, and `joblib.delayed` schedules a single instantiation of the function, and associated data, which is to be executed. We can execute a sequence of `delayed` tasks by passing them to the `Parallel` pool:
%% Cell type:code id:f96c07ac tags:
```
with joblib.Parallel(n_jobs=-1) as pool:
tasks = [joblib.delayed(do_calculation)(d) for d in datasets]
results = pool(tasks)
print(results)
```
%% Cell type:markdown id:f0b73045 tags:
Just like with `multiprocessing`, JobLib is susceptible to the same problems with regard to sharing data between processes (these problems are
discussed in the `advanced_programming/threading.ipynb` notebook). In the example above, each dataset is serialised and copied from the main process
to the worker processes, and then the result copied back. This behaviour could be a performance bottleneck for your own task, or you may be working
on a system with limited memory which is incapable of storing several copies of the data.
To deal with this, we can use memory-mapped Numpy arrays. This is a feature built into Numpy, and supported by JobLib, which stores your data in your file system instead of in memory. This allows your data to be simultaneously read and written by multiple processes.
You can create `numpy.memmap` arrays directly, but JobLib will also automatically convert any Numpy arrays which are larger than a specified threshold into memory-mapped arrays. This threshold defaults to 1MB, and you can change it via the `n_bytes` option when you create a `joblib.Parallel` pool.
To see this in action, imagine that you have some 4D fMRI data, and wish to fit a complicated model to the time series at each voxel. We will write our model fitting function so that it works on one slice at a time:
%% Cell type:code id:b2966ebe tags:
```
def fit_model(indata, outdata, sliceidx):
print(f'Fitting model at slice {sliceidx}')
time.sleep(1)
outdata[:, :, sliceidx] = indata[:, :, sliceidx, :].mean() + sliceidx
```
%% Cell type:markdown id:29e18767 tags:
Now we will load our 4D data, and pre-allocate another array to store the fitted model parameters.
%% Cell type:code id:b7f9b544 tags:
```
# Imagine that we have loaded this data from a file
data = np.random.random((91, 109, 91, 50)).astype(np.float32)
# Pre-allocate space to store the fitted model parameters
model = np.memmap('model.mmap',
shape=(91, 109, 91),
dtype=np.float32,
mode='w+')
# Fit our model, processing slices in parallel
with joblib.Parallel(n_jobs=-1) as pool:
pool(joblib.delayed(fit_model)(data, model, slc) for slc in range(91))
print(model)
```
%% Cell type:markdown id:851e0392 tags:
<a class="anchor" id="dask"></a>
# Dask
https://www.dask.org/
Dask is a very powerful library which you can use to parallelise your code, and to distribute computation across multiple machines. You can use Dask locally on your own computer, on HPC clusters (e.g. SLURM and SGE) and with cloud compute platforms (e.g. AWS, Azure).
Dask has two main components:
- APIs for defining tasks/jobs - there is a low-level API similar to that provided by JobLib, but Dask also has sophisticated high-level APIs for working with Pandas and Numpy-style data.
- A task scheduler which builds a graph of all the tasks that need to be executed, and which manges their execution, either locally or remotely.
We will introduce the Numpy API and will briefly cover the low-level API, and then demonstrate how to use Dask to perform calculations on a SGE cluster.
<a class="anchor" id="dask-numpy-api"></a>
## Dask Numpy API
To use the Dask Numpy API, simply import the `dask.array` package, and use it instead of the `numpy` package:
%% Cell type:code id:83f8a8df tags:
```
import numpy as np
import dask.array as da
data = da.random.random((1000, 1000, 1000, 20)).astype(float32)
```
%% Cell type:markdown id:ae58302e tags:
If you do the numbers, you will realise that the above call has created an array which requires **74 gigabytes** of memory - this is far more memory than what is available in most consumer level computers.
> The call would almost certainly fail if you made it using `np.random.random` instead of `da.random.random`, as Numpy will attempt to create the entire data set (and would actually temporarily require up to **150 gigabytes** of memory, as Numpy uses double-precision floating point (`float64`) values by default).
However:
- Dask automatically splits arrays into smaller chunks - in the above code, `data` has been split into 1331 smaller arrays, each of which has shape `(94, 94, 94, 10)`, and requires only 64 megabytes.
- Most operations in the `dask.array` package are _lazily evaluated_. The above call has not actually created any data - Dask has just created a set of jobs which describe how to create a large array of random values.
When using `dask.array`, nothing is actually executed until you call the `compute()` function. For example, we can try calculating the mean of our large array:
%% Cell type:code id:67fc4ec6 tags:
```
m = data.mean()
m
```
%% Cell type:markdown id:9a2d89c1 tags:
But again, this will not actually calculate the mean - it just defines a task which, when executed, will calculate the mean over the `data` array.
We can _execute_ that task by callintg `compute()` on the result:
%% Cell type:code id:0f60b5b3 tags:
```
print(m.compute())
```
%% Cell type:markdown id:5e51a09e tags:
<a class="anchor" id="low-level-dask-api"></a>
## Low-level Dask API
<a class="anchor" id="distributing-computation-with-dask"></a>
## Distributing computation with Dask
fsl-pipe
fsl_sub
ray
# Parallel processing in Python
While Python has built-in support for threading and parallelising in the
[`threading`](https://docs.python.org/3/library/threading.html) and
[`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html)
modules, there are a range of third-party libraries which you can use to improve the performance of your code.
Contents:
* [JobLib](#joblib)
* [Dask](#dask)
* [Dask Numpy API](#dask-numpy-api)
* [Low-level Dask API](#low-level-dask-api)
* [Distributing computation with Dask](#distributing-computation-with-dask)
* [fsl-pipe](#fsl-pipe)
<a class="anchor" id="joblib"></a>
# JobLib
https://joblib.readthedocs.io/en/stable/
JobLib has been around for a while, and is a simple and lightweight library with two main features:
- An API for "embarrassingly parallel" tasks.
- An API for caching/re-using the results of time-consuming computations.
On the surface, JobLib does not provide any functionality that cannot already be accomplished with built-in libraries such as `multiprocessing` and `functools`. However, the JobLib developers have put a lot of effort into ensuring that JobLib:
- is easy to use,
- works consistently across all of the major platforms, and
- works as efficiently as possible with Numpy arrays
We can use the JobLib API by importing the `joblib` package (we'll also use `numpy` and `time` in this example):
```
import numpy as np
import joblib
import time
```
Now, let's say that we have a collection of `numpy` arrays containing image data for a group of subjects:
```
datasets = [np.random.random((91, 109, 91)) for i in range(10)]
```
And we want to calculate some metric on each image. We simply need to define a function which contains the calculation we want to perform (the `time.sleep` call is there just to simulate a complex calculation):
```
def do_calculation(input_data):
time.sleep(2)
return input_data.mean()
```
We can now use `joblib.Parallel` and `joblib.delayed` to parallelise those calculations. `joblib.Parallel` sets up a pool of worker processes, and `joblib.delayed` schedules a single instantiation of the function, and associated data, which is to be executed. We can execute a sequence of `delayed` tasks by passing them to the `Parallel` pool:
```
with joblib.Parallel(n_jobs=-1) as pool:
tasks = [joblib.delayed(do_calculation)(d) for d in datasets]
results = pool(tasks)
print(results)
```
Just like with `multiprocessing`, JobLib is susceptible to the same problems with regard to sharing data between processes (these problems are
discussed in the `advanced_programming/threading.ipynb` notebook). In the example above, each dataset is serialised and copied from the main process
to the worker processes, and then the result copied back. This behaviour could be a performance bottleneck for your own task, or you may be working
on a system with limited memory which is incapable of storing several copies of the data.
To deal with this, we can use memory-mapped Numpy arrays. This is a feature built into Numpy, and supported by JobLib, which stores your data in your file system instead of in memory. This allows your data to be simultaneously read and written by multiple processes.
You can create `numpy.memmap` arrays directly, but JobLib will also automatically convert any Numpy arrays which are larger than a specified threshold into memory-mapped arrays. This threshold defaults to 1MB, and you can change it via the `n_bytes` option when you create a `joblib.Parallel` pool.
To see this in action, imagine that you have some 4D fMRI data, and wish to fit a complicated model to the time series at each voxel. We will write our model fitting function so that it works on one slice at a time:
```
def fit_model(indata, outdata, sliceidx):
print(f'Fitting model at slice {sliceidx}')
time.sleep(1)
outdata[:, :, sliceidx] = indata[:, :, sliceidx, :].mean() + sliceidx
```
Now we will load our 4D data, and pre-allocate another array to store the fitted model parameters.
```
# Imagine that we have loaded this data from a file
data = np.random.random((91, 109, 91, 50)).astype(np.float32)
# Pre-allocate space to store the fitted model parameters
model = np.memmap('model.mmap',
shape=(91, 109, 91),
dtype=np.float32,
mode='w+')
# Fit our model, processing slices in parallel
with joblib.Parallel(n_jobs=-1) as pool:
pool(joblib.delayed(fit_model)(data, model, slc) for slc in range(91))
print(model)
```
<a class="anchor" id="dask"></a>
# Dask
https://www.dask.org/
Dask is a very powerful library which you can use to parallelise your code, and to distribute computation across multiple machines. You can use Dask locally on your own computer, on HPC clusters (e.g. SLURM and SGE) and with cloud compute platforms (e.g. AWS, Azure).
Dask has two main components:
- APIs for defining tasks/jobs - there is a low-level API similar to that provided by JobLib, but Dask also has sophisticated high-level APIs for working with Pandas and Numpy-style data.
- A task scheduler which builds a graph of all the tasks that need to be executed, and which manges their execution, either locally or remotely.
We will introduce the Numpy API and will briefly cover the low-level API, and then demonstrate how to use Dask to perform calculations on a SGE cluster.
<a class="anchor" id="dask-numpy-api"></a>
## Dask Numpy API
To use the Dask Numpy API, simply import the `dask.array` package, and use it instead of the `numpy` package:
```
import numpy as np
import dask.array as da
data = da.random.random((1000, 1000, 1000, 20)).astype(float32)
```
If you do the numbers, you will realise that the above call has created an array which requires **74 gigabytes** of memory - this is far more memory than what is available in most consumer level computers.
> The call would almost certainly fail if you made it using `np.random.random` instead of `da.random.random`, as Numpy will attempt to create the entire data set (and would actually temporarily require up to **150 gigabytes** of memory, as Numpy uses double-precision floating point (`float64`) values by default).
However:
- Dask automatically splits arrays into smaller chunks - in the above code, `data` has been split into 1331 smaller arrays, each of which has shape `(94, 94, 94, 10)`, and requires only 64 megabytes.
- Most operations in the `dask.array` package are _lazily evaluated_. The above call has not actually created any data - Dask has just created a set of jobs which describe how to create a large array of random values.
When using `dask.array`, nothing is actually executed until you call the `compute()` function. For example, we can try calculating the mean of our large array:
```
m = data.mean()
m
```
But again, this will not actually calculate the mean - it just defines a task which, when executed, will calculate the mean over the `data` array.
We can _execute_ that task by callintg `compute()` on the result:
```
print(m.compute())
```
<a class="anchor" id="low-level-dask-api"></a>
## Low-level Dask API
<a class="anchor" id="distributing-computation-with-dask"></a>
## Distributing computation with Dask
fsl-pipe
fsl_sub
ray
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment