dask performance apply along axis

廉价感情. 提交于 2021-02-07 09:35:25

问题


I am trying to compute the linear trend over time on a large high resolution ocean model dataset using dask.

I have followed this example (Applying a function along an axis of a dask array) and found the syntax of apply_along_axis easier.

I am currently using dask.array.apply_along_axis to wrap a numpy function on 1 dimensional arrays and then package the resulting dask array into an xarray Dataarray. Using top -u <username> suggest that the computation is not executed in parallel (~100% cpu use).

Should I expect a better performance from map_blocks? Or are there any suggestions on how to improve the performance of apply_along_axis? Any tips are highly appreciated.

import numpy as np
from scipy import optimize
import xarray as xr
import dask.array as dsa

def _lin_trend(y):
    x = np.arange(len(y))
    return np.polyfit(x, y, 1)



def linear_trend(da, dim, name='parameter'):
    da = da.copy()
    axis_num = da.get_axis_num(dim)

    dims = list(da.dims)
    dims[axis_num] = name
    coords = da.rename({dim:name}).coords
    coords[name] = ['slope', 'intercept']

    dsk = da.data
    dsk_trend = dsa.apply_along_axis(_lin_trend,0,dsk)
    out = xr.DataArray(dsk_trend, dims=dims, coords=coords)
    return out

回答1:


I have been doing something similar using xarray's apply_ufunc (requires xarray v0.10 or later). This is likely to be a bit easier to manage than using the apply_along_axis function in dask.

import xarray as xr
import numpy as np
from scipy import stats

def _calc_slope(x, y):
    '''wrapper that returns the slop from a linear regression fit of x and y'''
    slope = stats.linregress(x, y)[0]  # extract slope only
    return slope


def linear_trend(obj):
    time_nums = xr.DataArray(obj['time'].values.astype(np.float),
                             dims='time',
                             coords={'time': obj['time']},
                             name='time_nums')
    trend = xr.apply_ufunc(_calc_slope, time_nums, obj,
                           vectorize=True,
                           input_core_dims=[['time'], ['time']],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend

Addressing your question about why the performance isn't as expected. This could be from a number of reasons. How is your dask array chunked? Which dask scheduler are you using? I'll update the second part of my answer after I get a better idea what your configuration is?




回答2:


I think that ultimately the performance is limited by the filesystem I am working on. To answer your question though, my dataset has the following shape:

<xarray.Dataset>
Dimensions:         (st_edges_ocean: 51, st_ocean: 50, time: 101, xt_ocean: 3600, yt_ocean: 2700)
Coordinates:
  * xt_ocean        (xt_ocean) float64 -279.9 -279.8 -279.7 -279.6 -279.5 ...
  * yt_ocean        (yt_ocean) float64 -81.11 -81.07 -81.02 -80.98 -80.94 ...
  * st_ocean        (st_ocean) float64 5.034 15.1 25.22 35.36 45.58 55.85 ...
  * st_edges_ocean  (st_edges_ocean) float64 0.0 10.07 20.16 30.29 40.47 ...
  * time            (time) float64 3.634e+04 3.671e+04 3.707e+04 3.744e+04 ...

So it is rather big and needs a long time to read from disk. I have rechunked it so that the time dimension is a single chunk

dask.array<concatenate, shape=(101, 50, 2700, 3600), dtype=float64, 
chunksize=(101, 1, 270, 3600)>

That did not make a big difference for the performance (it still takes about 20 hrs for the function to finish (that is including reading and writing to disk). I am currently only chunking in time, e.g.

dask.array<concatenate, shape=(101, 50, 2700, 3600), dtype=float64, 
chunksize=(1, 1, 2700, 3600)>

I was interested in the relative performance of both methods and ran a test on my laptop.

import xarray as xr
import numpy as np
from scipy import stats
import dask.array as dsa

slope = 10
intercept = 5
t = np.arange(250)
x = np.arange(10)
y = np.arange(500)
z = np.arange(200)
chunks = {'x':10, 'y':10}

noise = np.random.random([len(x), len(y), len(z), len(t)])
ones = np.ones_like(noise)
time = ones*t
data = (time*slope+intercept)+noise
da = xr.DataArray(data, dims=['x', 'y', 'z', 't'],
                 coords={'x':('x', x),
                        'y':('y', y),
                        'z':('z', z),
                        't':('t', t)})
da = da.chunk(chunks)
da

I now defined a set of private functions (using both linregress and polyfit to calculate the slope of a timeseries), as well as different implementations using dask.apply_along and xarray.apply_ufunc.

def _calc_slope_poly(y):
    """ufunc to be used by linear_trend"""
    x = np.arange(len(y))
    return np.polyfit(x, y, 1)[0]


def _calc_slope(y):
    '''returns the slop from a linear regression fit of x and y'''
    x = np.arange(len(y))
    return stats.linregress(x, y)[0]

def linear_trend_along(da, dim):
    """computes linear trend over 'dim' from the da.
       Slope and intercept of the least square fit are added to a new
       DataArray which has the dimension 'name' instead of 'dim', containing
       slope and intercept for each gridpoint
    """
    da = da.copy()
    axis_num = da.get_axis_num(dim)
    trend = dsa.apply_along_axis(_calc_slope, axis_num, da.data)
    return trend

def linear_trend_ufunc(obj, dim):
    trend = xr.apply_ufunc(_calc_slope, obj,
                           vectorize=True,
                           input_core_dims=[[dim]],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend

def linear_trend_ufunc_poly(obj, dim):
    trend = xr.apply_ufunc(_calc_slope_poly, obj,
                           vectorize=True,
                           input_core_dims=[[dim]],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend

def linear_trend_along_poly(da, dim):
    """computes linear trend over 'dim' from the da.
       Slope and intercept of the least square fit are added to a new
       DataArray which has the dimension 'name' instead of 'dim', containing
       slope and intercept for each gridpoint
    """
    da = da.copy()
    axis_num = da.get_axis_num(dim)
    trend = dsa.apply_along_axis(_calc_slope_poly, axis_num, da.data)
    return trend

trend_ufunc = linear_trend_ufunc(da, 't')
trend_ufunc_poly = linear_trend_ufunc_poly(da, 't')
trend_along = linear_trend_along(da, 't')
trend_along_poly = linear_trend_along_poly(da, 't')

Timing the computation seems to indicate that the apply_along method might be marginally faster. Using polyfit instead of linregress seems to have quite a big influences though. I am not sure why this is much faster but perhaps this is of interest to you.

%%timeit 
print(trend_ufunc[1,1,1].data.compute())

4.89 s ± 180 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit 
trend_ufunc_poly[1,1,1].compute()

2.74 s ± 182 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit 
trend_along[1,1,1].compute()

4.58 s ± 193 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
trend_along_poly[1,1,1].compute()

2.64 s ± 65 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)



来源:https://stackoverflow.com/questions/47314800/dask-performance-apply-along-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!