Ouranosinc / xclim-benchmark

MIT License
0 stars 0 forks source link

Rolling benchmarks #1

Closed aulemahal closed 4 years ago

aulemahal commented 4 years ago

I think I finally decrypted the strange behaviour of the rolling methods and their memory consumption.

This PR adds the benchmarking script that generated the graphs below.

The conclusion is that we should revert to xarray's rolling method, but calling the rolled function with skipna=False, allow_lazy=True. xclim.utils._rolling consumes slightly less memory, but not enough to justify a in-house algorithm.

The rolling method goes through 3 steps:

  1. Construct a new array with an added rolling dimension
  2. Reduce this array with the given function
  3. Repeat, but with data.notnull() to count the number of valid values in each window.
  4. Return an array filtered by the count of #3.

As of xarray 0.14.1, the reduce method of step 2 had an hard coded allow_lazy = False. This was fixed by pydata/xarray#3435. Other than the problem of being not lazy, this triggered huge memory consumption has shown in this graph:

rolling_memuse_max_120x81MB_client32threads_NotLazy_skipnaTrue

Adding allow_lazy=True to the call solves most of the problem. However, by default, xarray uses the nanops (nanmean, nanmax, etc.), which are slower than their nan-oblivious counterparts. This is useful if the min_periods argument is smaller than window, but otherwise, there is no use. Passing skipna=False does help a bit and uses only slightly more memory than xclim's _rolling as seen here:

rolling_memuse_mean_120x81MB_client32threads_lazy_skipnaTrue

That's for sum or mean, xclim's current implementation for any other function consumes as much memory as the one in xarray and is even slighlty slower.

rolling_memuse_max_120x81MB_client32threads_lazy_skipnaTrue

As seen on the graphs, simply ignoring the nan tests could save a lot of memory and even some time. For most cases nan-oblivious functions, nan is returned as soon as one value is nan. When skipna=False and min_periods==window, the counting step is thus useless. Furthermore, it simplifies the dask graph, which is always good. Maybe an option could be added to xarray's rolling for this?

Finally, all those result depend on the fact that bottleneck is not used with dask arrays in the current xarray as per issue pydata/xarray#2940 and PR pydata/xarray#3040.