Performance with dask and numba#
Introduction#
Many computations work along a single dimension, like a vertical interpolation, a
mixed layer depth or a tidal analysis, on arrays of dimensions like (time, z, y, x).
This guide explains how xoa processes them to be fast and to use little memory,
with numpy and dask arrays, and how to choose the dask scheduler.
In [1]: import numpy as np
In [2]: import xarray as xr
In [3]: from xoa import grid
In [4]: from xoa.core import num
The working dimension is kept in place#
xarray.apply_ufunc() moves the working dimension, also called the core dimension,
to the end, which transposes the arrays and often copies them.
The numba kernels of xoa rather keep it in place: an array of shape
(nt, nz, ny, nx) is viewed as (nouter, nz, ninner) with
nouter = nt and ninner = ny * nx, which is a reshape without a copy.
The kernels then loop in parallel on the nouter * ninner columns.
The other arrays, like the coordinates, may have only some of the dimensions.
xoa.core.num.broadcast_along_axis() views them as (mouter, n, minner),
where mouter and minner are 1 or the full sizes, so that a depth of dimensions
(z, y, x) is not copied for each time step:
In [5]: data = np.ones((3, 10, 4, 5)) # (t, z, y, x)
In [6]: depth = np.ones((10, 4, 5)) # (z, y, x)
In [7]: levels = np.ones((20, 1, 1)) # (zo,)
In [8]: views, outer, inner = num.broadcast_along_axis(data, depth, levels, axis=1)
In [9]: [view.shape for view in views]
Out[9]: [(3, 10, 20), (1, 10, 20), (1, 20, 1)]
At the xarray level, xoa.grid.map_along_dim() gives the arrays to such a function
with all the dimensions in the same order, and processes the dask arrays block by block:
In [10]: def double(data, axis):
....: return np.repeat(data, 2, axis=axis)
....:
In [11]: da = xr.DataArray(np.ones((3, 4, 5)), dims=("time", "z", "x"))
In [12]: grid.map_along_dim(double, da, "z", out_size=8).dims
Out[12]: ('time', 'z', 'x')
This is used by xoa.regrid.regrid1d(), xoa.regrid.extrap1d(),
xoa.interp.isoslice() and xoa.thermdyn.get_n2().
The tidal analyses, predictions and diagnostics of xoa.tide use it too, with the time dimension kept in place.
Dask arrays#
The working dimension is the one along which the kernel computes, like z for a
vertical interpolation. It must be a single chunk, and the other dimensions keep their
chunks, so chunk your data along the other dimensions. We recommend one block per
time step:
ds = xr.open_dataset("model.nc", chunks={"time": 1})
temp = xoa.regrid.regrid1d(ds.temp, levels)
If a single time step does not fit in memory, chunk y and x too,
like chunks={"time": 1, "y": 500, "x": 500}, but never z here.
The working dimension z is never split: a block is a time step (left) or a tile of
a time step (right).#
The memory is then about the number of blocks processed at the same time, times the size of an input block and of an output block.
Threads or processes?#
Use threads, which is the default scheduler of dask. They share the memory, so the blocks are not copied, and the numba kernels release the GIL, so the threads really run in parallel. With processes, each worker imports numpy, numba and xarray again, and the blocks are copied between the processes: in our tests, it was slower and used four times more memory.
Speed or memory#
With the threads scheduler, num_workers is the number of dask threads, which is
the number of blocks processed at the same time, hence the memory. The number of numba
threads, set with numba.set_num_threads(), is the number of threads of the
prange loops of the kernel, which is the parallelism within a block:
With num_workers=2 and numba.set_num_threads(4): 2 dask threads take 2 blocks
at the same time, and 4 numba threads compute in each of them, so 8 cpus are used.
The other blocks wait for a free dask thread.#
import dask
import numba
# Lowest memory: one block at a time, with all the numba threads inside
with dask.config.set(scheduler="synchronous"):
temp.to_netcdf("temp.nc")
# A compromise: 2 blocks at a time, with 4 numba threads each
numba.set_num_threads(4)
with dask.config.set(scheduler="threads", num_workers=2):
temp.to_netcdf("temp.nc")
# Fastest: as many blocks as cpus, and the most memory
temp.to_netcdf("temp.nc")
More dask workers do not speed up the computation itself, since the numba kernels
already use all the cpus: in the figures below, one block at a time is as fast as 8 workers.
They are useful when the data are read from and written to files, which often takes
most of the time: the input and output of some blocks then overlap the computation of
others, at the cost of more blocks in memory. So start with one block at a time, and
increase num_workers only if the input and output dominate.
The numba threading layer#
Several dask threads may call the parallel numba kernels at the same time.
The workqueue threading layer of numba does not support it, unlike the omp
and tbb ones, which are used when OpenMP or TBB are available.
Check it with numba.threading_layer() after a first computation, and see
the numba documentation
to select one.
Some figures#
Vertical interpolation of a (16, 40, 300, 400) array of 614 MB from sigma levels
to 50 fixed depths with xoa.regrid.regrid1d(), on 8 cpus, compared to the former
implementation with xarray.apply_ufunc():
Mode |
Speed up |
Memory |
|---|---|---|
numpy |
1.4 to 1.6 |
halved: only the output is allocated |
dask, one block at a time |
1.9 to 2.1 |
same |
dask, 8 workers |
1.8 to 2.0 |
same |
With depths that don’t have the time dimension, xoa.interp.isoslice() is
5 times faster with numpy, since the depths are no longer broadcasted to the shape
of the data, which also saves the memory of a copy of the data.