Skip to content

feature request da.overlapped_from_array to avoid memory copy when overlapping an array #4154

Open

Description

@hmaarrfk

Would the a addition of a method da.overlapped_from_array be appropriate.

In this method, under the applicable circumstances, an overlapped array is created from a single memory view into an existing numpy array. This would solve the da.from_array, da.overlapped issue whereby a fully new array is created when overlapping regions.

I think this kind of stuff would really help people ease into dask. It would definitely help the scikit-image community which probably has most of their code written for a single CPU.

Anyway, this isn't a bottlekneck for me now, but I just wanted to put it out there since it seems like overlapping computations is gaining more attention.

cc. @jakirkham

Activity

  1. jakirkham commented on Oct 31, 2018

    @jakirkham
    Member

    This is useful feedback to have. Thanks for raising this @hmaarrfk.

    Given you have played a bit with da.map_overlap's internals, are there particular points you know of in the current implementation where copies are being created? Would it be possible in your opinion to adjust those to take views without making copies? How difficult might such an effort be?

    Just trying to get a sense of what you think can and cannot be done within the existing API.

  2. hmaarrfk commented on Oct 31, 2018

    @hmaarrfk
    ContributorAuthor

    You raise an excellent point.

    Honestly, I used to think that numpy operated on strided arrays internally, but I'm increasingly convinced that they do not. It is pretty hard to read numpy C source code though. It is really dense and uses many macros to template things. So I could be wrong.

    I guess when I originally thought of this addition to the API it was thinking that numpy could natively operate on strided arrays.

    Here is a little benchmark I that clearly shows the limitations of numpy to operate on straightforward strided arrays:

    Benchmark
    import numpy as np
    
    chunk_size = (1000, 1000)
    # Create a largeish array. The importance is likely "out of cache"
    arr = np.full((10_000, 10_000), fill_value=1, dtype=np.float32)
    
    N_chunks = [shape // chunk for shape, chunk in zip(arr.shape, chunk_size)]
    # Create a few distinct contiguous arrays
    arrs_contiguous = []
    for i in range(N_chunks[0]):
        inner_arrs = []
        for j in range(N_chunks[1]):
            inner_arrs.append(np.full(chunk_size, fill_value=1, dtype=np.float32))
        arrs_contiguous.append(inner_arrs)
    
    arrs_sliced = []
    for i in range(N_chunks[0]):
        inner_arrs = []
        for j in range(N_chunks[1]):
            chunk_slice = np.s_[chunk_size[0]*i:chunk_size[0]*(i+1), chunk_size[1]*j:chunk_size[1]*(j+1)]
            inner_arrs.append(arr[chunk_slice])
        arrs_sliced.append(inner_arrs)
    %%timeit 
    
    # Baseline performance
    # arr += 1
    np.add(arr, 1, out=arr)

    31.8 ms ± 252 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

    %%timeit 
    # Looping slowdown
    for inner_arrs in arrs_sliced:
        for the_arr in inner_arrs:
            pass
        
    # Is insignificant

    1.11 µs ± 5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

    %%timeit
    # 5x slower
    for inner_arrs in arrs_sliced:
        for the_arr in inner_arrs:
            # Both are equivalent in terms of speed
            #the_arr += 1
            np.add(the_arr, 1, out=the_arr)

    159 ms ± 650 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

    %%timeit
    for inner_arrs in arrs_contiguous:
        for the_arr in inner_arrs:
            the_arr += 1
    # Much better in terms of performance.

    37.2 ms ± 6.09 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

    arrs_sliced[0][0].strides

    (40000, 4)

    Performance isn't as bad as:

    %%timeit
    # 9x slower
    for inner_arrs in arrs_sliced:
        for the_arr in inner_arrs:
            tmp = the_arr + 1
            the_arr = tmp
    

    241 ms ± 5.03 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

    Seemes like this kind of stuff could really benefit from real JIT or higher level compilation.
    Adding 1000 floats together is basically a whole cache line. It should be pretty well optimized, though it seems like it isn't in the case where the array isn't c-contiguous.

    CC ing: @serge-sans-paille has some comments as to how pythran might deal with this. I know he made use of heavy AVX instructions and likely had to think about this contiguous/non-contiguous types of operations alot.

  3. hmaarrfk commented on Oct 31, 2018

    @hmaarrfk
    ContributorAuthor

    Here is my best attempt at using numba

    Details
    from numba import njit, jit
    import numba
    @njit(numba.void(numba.float32[::1]))
    def add_row(b):
        b += 1
    @jit
    def my_add_1(a):
        for i in range(a.shape[0]):
            add_row(a[i])
            
    # This doesn't perform any better than numpy
    @njit(numba.void(numba.float32[:, ::1]))
    def add_2d(a):
        a += 1

    compile

    my_add_1(arrs_sliced[0][0])
    %%timeit
    for inner_arrs in arrs_sliced:
        for the_arr in inner_arrs:
            my_add_1(the_arr)

    77.7 ms ± 715 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

  4. serge-sans-paille commented on Nov 1, 2018

    @serge-sans-paille
  5. hmaarrfk commented on Nov 1, 2018

    @hmaarrfk
    ContributorAuthor

    Man, life and compilers is hard: This typo (which forces the arrays to be square):

    Details ```python from numba import njit, jit import numba @njit def add_2d_loops(a): for i in range(a.shape[0]): for j in range(a.shape[0]): # <- should be shape[1] a[i, j] += 1

    @njit # (numba.void(numba.float32[:, ::1]))
    def add_2d(a):
    a += 1

    Gives you near equal performance
    ```python
    %%timeit
    for inner_arrs in arrs_sliced:   # arrs_contiguous:
        for the_arr in inner_arrs:
            add_2d_loops(the_arr)
    
    * 35 ms vs 30 ms

    Fixing the typo, drops you to

    • 110 vs 30 ms

    But in our particular toy example, both the typo an the fixed typo give the same result in terms of input output response.

  6. hmaarrfk commented on Nov 1, 2018

    @hmaarrfk
    ContributorAuthor

    In the original post where I created chunked arrays, there was a typo in the calculation of the chunk_slice. It didn't affect the results when the arrays were being chunked with (1000, 1000), but it did create strange results with chunks of (100, 10_000)

    The bug was that I used chunk_size[1] * i, when it should be chunk_size[1] * j

  7. jakirkham commented on Apr 30, 2019

    @jakirkham
    Member

    Is this feature still of interest to you, @hmaarrfk? Would you be interested in submitting a PR?

  8. hmaarrfk commented on Apr 30, 2019

    @hmaarrfk
    ContributorAuthor

    Oh man, my work has made me jump down the rabbit hole of performance unfortunately.

    I still haven't had the time to create real benchmarks for how things work on strided arrays.

    Thinking of memory models has been big on my priority list, but I haven't had too much time to focus on it.

    In other performance related PRs I issued, the main question was: "who is this improvement for".

    For example

    $ ipython                                                                                               
    import Python 3.7.1 | packaged by conda-forge | (default, Feb 18 2019, 01:42:00) 
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: import numpy as np                                                                              
    
    In [2]: a = np.random.rand(1024, 1024)                                                                  
    
    In [3]: %timeit a + a                                                                                   
    812 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [4]: %timeit a[::2] + a[::2]                                                                         
    654 µs ± 15.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [5]: %timeit a[:, ::2] + a[:, ::2]                                                                   
    598 µs ± 11.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [6]: %timeit a[:512] + a[:512]                                                                       
    323 µs ± 8.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [7]: np.__version__                                                                                  
    Out[7]: '1.15.4'

    (Ok i seriously thought i had 1.16 installed, but this kinda illustrates the point).

    depending on how the memory is organized, and how numpy does strided computation, it is unclear that there is any benefit of storing arrays in "strided" format.

    I would have to compare this to what hand tuned strided operation are able to achieve.

    My general fear, is that in an attempt to speed things up for a particular use case, we would slow everything down for all other use cases....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions