Skip to content

Applying a function to each chunk in a Dask array and combining the results (output is a different shape to the array) #7589

Closed

Description

@GenevieveBuckley

What happened:
I run into this type of pattern a lot.

I want to do $foo to all the chunks (or slightly overlapping chunks) in a Dask array. I can't use map_overlap or map_blocks easily, because what I get back from the function $foo isn't the same shape as the original array - it's a list, or multiple lists, could be a pandas series or dataframe.

I need to combine all of these outputs. In the simplest case, I don't care which array chunk they were generated from, I just want to append all the results together.

What you expected to happen:
Matt and I both initially expected that we should be able to use map_blocks for this kind of situation.

Minimal Complete Verifiable Example:

import dask.array as da
import numpy as np
x = da.ones((100, 10), chunks=(10, 10))

def foo(a):
    return np.array([1, 2, 3])

result = da.map_blocks(foo, x)
result.compute()

But because the result from foo isn't the same shape as the input array chunk, we get this error:

Details:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-30-80557264a235> in <module>
      7 
      8 result = da.map_blocks(foo, x)
----> 9 result.compute()

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in compute(self, **kwargs)
    282         dask.base.compute
    283         """
--> 284         (result,) = compute(self, traverse=False, **kwargs)
    285         return result
    286 

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in compute(*args, **kwargs)
    565 
    566     results = schedule(dsk, keys, **kwargs)
--> 567     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    568 
    569 

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in <listcomp>(.0)
    565 
    566     results = schedule(dsk, keys, **kwargs)
--> 567     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    568 
    569 

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in finalize(results)
   1073     while isinstance(results2, (tuple, list)):
   1074         if len(results2) > 1:
-> 1075             return concatenate3(results)
   1076         else:
   1077             results2 = results2[0]

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in concatenate3(arrays)
   4757     if not ndim:
   4758         return arrays
-> 4759     chunks = chunks_from_arrays(arrays)
   4760     shape = tuple(map(sum, chunks))
   4761 

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in chunks_from_arrays(arrays)
   4528 
   4529     while isinstance(arrays, (list, tuple)):
-> 4530         result.append(tuple([shape(deepfirst(a))[dim] for a in arrays]))
   4531         arrays = arrays[0]
   4532         dim += 1

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in <listcomp>(.0)
   4528 
   4529     while isinstance(arrays, (list, tuple)):
-> 4530         result.append(tuple([shape(deepfirst(a))[dim] for a in arrays]))
   4531         arrays = arrays[0]
   4532         dim += 1

IndexError: tuple index out of range

Anything else we need to know?:

Environment:

  • Dask version: '2021.04.0'
  • Python version: 3.8
  • Operating System: Ubuntu 20.04 LTS
  • Install method (conda, pip, source): conda

Activity

  1. GenevieveBuckley commented on Apr 22, 2021

    @GenevieveBuckley
    ContributorAuthor

    For reference, here are the examples Matt tried involving pandas output from function foo. I'm including them here for reference, although I think the fundamental problem is described more simply by the MCVE above.

    With a pandas Series

    import dask.array as da
    import pandas as pd
    
    x = da.ones((100, 10), chunks=(10, 10))
    
    def foo(a):
        return pd.Series([1, 2, 3])
    
    result = da.map_blocks(foo, x)
    result.compute()
    Error message details:
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-33-a4f886589eb2> in <module>
    ----> 1 result.compute()
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in compute(self, **kwargs)
        282         dask.base.compute
        283         """
    --> 284         (result,) = compute(self, traverse=False, **kwargs)
        285         return result
        286 
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in compute(*args, **kwargs)
        558     )
        559 
    --> 560     dsk = collections_to_dsk(collections, optimize_graph, **kwargs)
        561     keys, postcomputes = [], []
        562     for x in collections:
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in collections_to_dsk(collections, optimize_graph, optimizations, **kwargs)
        334         for opt, val in groups.items():
        335             dsk, keys = _extract_graph_and_keys(val)
    --> 336             dsk = opt(dsk, keys, **kwargs)
        337 
        338             for opt in optimizations:
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/dataframe/optimize.py in optimize(dsk, keys, **kwargs)
         39         fuse_subgraphs=fuse_subgraphs,
         40     )
    ---> 41     dsk, _ = cull(dsk, keys)
         42     return dsk
         43 
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/optimization.py in cull(dsk, keys)
         49         new_work = []
         50         for k in work:
    ---> 51             dependencies_k = get_dependencies(dsk, k, as_list=True)  # fuse needs lists
         52             out[k] = dsk[k]
         53             dependencies[k] = dependencies_k
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/core.py in get_dependencies(dsk, key, task, as_list)
        250     """
        251     if key is not None:
    --> 252         arg = dsk[key]
        253     elif task is not no_default:
        254         arg = task
    
    KeyError: ('foo-78edf44570908b37e2606346af577beb', 1)
    

    With a pandas dataframe

    import dask.array as da
    import pandas as pd
    
    x = da.ones((100, 10), chunks=(10, 10))
    
    def foo(a):
        return pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
    
    result = da.map_blocks(foo, x)
    Error message details:
    --------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-6-4fc9e129d074> in <module>
    ----> 1 result = da.map_blocks(foo, x)
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in map_blocks(self, func, *args, **kwargs)
       2313     @wraps(map_blocks)
       2314     def map_blocks(self, func, *args, **kwargs):
    -> 2315         return map_blocks(func, self, *args, **kwargs)
       2316 
       2317     def map_overlap(self, func, depth, boundary=None, trim=True, **kwargs):
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in map_blocks(func, name, token, dtype, chunks, drop_axis, new_axis, meta, *args, **kwargs)
        681             pass
        682 
    --> 683         dtype = apply_infer_dtype(func, args, original_kwargs, "map_blocks")
        684 
        685     if drop_axis:
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in apply_infer_dtype(func, args, kwargs, funcname, suggest_dtype, nout)
        407     if msg is not None:
        408         raise ValueError(msg)
    --> 409     return o.dtype if nout is None else tuple(e.dtype for e in o)
        410 
        411 
    
    ~/anaconda3/envs/dask/lib/python3.8/site-packages/pandas/core/generic.py in __getattr__(self, name)
       5463             if self._info_axis._can_hold_identifiers_and_holds_name(name):
       5464                 return self[name]
    -> 5465             return object.__getattribute__(self, name)
       5466 
       5467     def __setattr__(self, name: str, value) -> None:
    
    AttributeError: 'DataFrame' object has no attribute 'dtype'
  2. GenevieveBuckley commented on Apr 22, 2021

    @GenevieveBuckley
    ContributorAuthor

    I was trying to work around this problem earlier by using blockwise with ragged outputs, but I couldn't quite work out how to make it work for 2D or nD arrays - #7551

  3. chrisroat commented on Apr 22, 2021

    @chrisroat
    Contributor

    You can use a delayed function on each chunk. I think map_{blocks,overlap} are very array-specific, but you could imagine creating another function to handle this.

    import dask.array as da
    import dask.dataframe as dd
    import numpy as np
    import pandas as pd
    import dask
    
    np.random.seed(42)  # To geterministic results
    
    x = da.ones((20, 10), chunks=(10, 10))
    
    @dask.delayed
    def foo(a):
        size = np.random.randint(1,10)  # Make each dataframe a different size
        return pd.DataFrame({'x': np.arange(size), 
                             'y': np.arange(10, 10+size)})
    
    meta = dd.utils.make_meta([('x', np.int64), ('y', np.int64)])
    blocks = x.to_delayed().ravel()
    results = [dd.from_delayed(foo(b), meta=meta) for b in blocks]  # edited to include meta parameter
    ddf = dd.concat(results)
    ddf.compute()
       x   y
    0  0  10
    1  1  11
    2  2  12
    3  3  13
    4  4  14
    5  5  15
    6  6  16
    7  7  17
    0  0  10
    1  1  11
    2  2  12
    3  3  13
    4  4  14
    
  4. chrisroat commented on Apr 22, 2021

    @chrisroat
    Contributor

    And for completeness, here's how to do it with arrays:

    import dask.array as da
    import numpy as np
    import dask
    
    np.random.seed(42)
    
    x = da.ones((20, 10), chunks=(10, 10))
    
    @dask.delayed
    def foo(a):
        size = np.random.randint(1,10)
        return np.random.randint(1,10, size=(2, size))
    
    blocks = x.to_delayed().ravel()
    results = [da.from_delayed(foo(b), shape=(2, np.nan), dtype=np.int64) for b in blocks]
    arr = da.concatenate(results, axis=1, allow_unknown_chunksizes=True)
    arr.compute()
    array([[4, 8, 5, 7, 3, 7, 8, 8, 6],
           [5, 4, 8, 8, 3, 6, 5, 2, 5]])
    
  5. chrisroat commented on Apr 22, 2021

    @chrisroat
    Contributor

    If you want to know the chunk indices, you can do something similar to what is done in dask-image. Note that they use slicing to get chunks, whereas here I use to_delayed().ravel(). I believe it should be the same.

  6. GenevieveBuckley commented on Apr 22, 2021

    @GenevieveBuckley
    ContributorAuthor

    You can use a delayed function on each chunk.

    Yes, this is true.

    The reason for raising this issue is:

    • Intuitively expecting this is supported seems to be an easy misperception to fall into, and
    • This type of pattern is pretty common towards the end of analysis pipelines, so perhaps we should cater for it more.
  7. chrisroat commented on Apr 22, 2021

    @chrisroat
    Contributor

    Agree that it is useful! I have used examples of this in my work. A unified meta argument, which could be either an array or dataframe, could be a usable interface.

  8. jsignell commented on Apr 22, 2021

    @jsignell
    Member

    You can use the drop_axis to alter the dimensionality of the output. For example in your case above you can do:

    result = da.map_blocks(foo, x, chunks=(3,), drop_axis=0).compute()
    # array([1, 2, 3])
    
    # OR
    result = da.map_blocks(foo, x, chunks=(3,), drop_axis=1).compute()
    # array([1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1,
    #        2, 3, 1, 2, 3, 1, 2, 3])

    It's not clear to me from your original problem statement? Are you looking for the output to be 1D?

  9. chrisroat commented on Apr 22, 2021

    @chrisroat
    Contributor
  10. jsignell commented on Apr 22, 2021

    @jsignell
    Member

    Ah ok like this?

    In  [1]: import dask.array as da
        ...: import numpy as np
        ...: x = da.ones((100, 10), chunks=(10, 10))
        ...: 
        ...: def foo(a, block_id=None):
        ...:     ii = block_id[0]
        ...:     return np.arange(ii)
        ...: 
        ...: result = da.map_blocks(foo, x, chunks=(tuple(range(0, 10)),), dtype=int, drop_axis=1)
        ...: result.compute()
    Out [1]: 
    array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 0,
           1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
           8])
    

    Note that the chunks kwarg is only required if you want the result.chunks and result.size to be accurate. result.compute() will work fine without it.

  11. jsignell commented on Apr 22, 2021

    @jsignell
    Member

    If the intention is to have ragged arrays in each block and not concatenate, then I think this is not a good use of dask.array. It'd probably make more sense as a bag of arrays or something.

  12. chrisroat commented on Apr 22, 2021

    @chrisroat
    Contributor
  13. jsignell commented on Apr 26, 2021

    @jsignell
    Member

    Is your thought to start with an array, turn each chunk into a member of a bag,
    then map a function (array->dataframe) on the array bag, and then dd.concat
    the dataframe bag?

    Clearly, I don't have a great understanding of this workflow so feel free to ignore me if this isn't helpful :) but what I was thinking was that you would start with an array and then the output of each chunk would be a bag. I agree that it's very similar to the approach that you gave @chrisroat - I was just trying to avoid the initial to_delayed step.

  14. chrisroat commented on Apr 26, 2021

    @chrisroat
    Contributor

    Clearly, I don't have a great understanding of this workflow so feel free to ignore me if this isn't helpful :) but what I was thinking was that you would start with an array and then the output of each chunk would be a bag. I agree that it's very similar to the approach that you gave @chrisroat - I was just trying to avoid the initial to_delayed step.

    That sounds like a similar approach, but I'm not sure how one avoids to_delayed or dask.delayed. How can one convert each chunk to a bag without going through something delayed?

  15. GenevieveBuckley commented on Apr 27, 2021

    @GenevieveBuckley
    ContributorAuthor

    Thanks @chrisroat and @jsignell, it's really great to see these other examples.

    You are correct that it is ragged in every dimension, so an array output is
    not going to work.

    I personally have one ragged dimension, which I do want to concatenate the results along. It seems there are more variations on what other people want to do than I'd guessed, which is useful information to know.

  16. 8 remaining items

  17. GenevieveBuckley commented on May 3, 2021

    @GenevieveBuckley
    ContributorAuthor

    Ok, now I'll give up. I've just been digging into it again & it's not going to be as straightforward as I'd hoped to change the way the map_overlap results get concatenated back together.

    @jakirkham perhaps it's worth us having a discussion about this particular use case (taking slightly overlapping chunks of a dask array, applying an arbitrary function on them, and then being able to combine different shaped results from each chunk)

  18. chrisroat commented on May 3, 2021

    @chrisroat
    Contributor

    Can you try adding the meta parameter? I see that my original example didn't include that -- I've updated it.

  19. GenevieveBuckley commented on May 4, 2021

    @GenevieveBuckley
    ContributorAuthor

    Can you try adding the meta parameter? I see that my original example didn't include that -- I've updated it.

    Ah, much better now! Thanks @chrisroat

  20. jni commented on May 12, 2021

    @jni
    Contributor

    A truly fascinating discussion — thanks all!

    I am just writing to echo @GenevieveBuckley's sentiment that it should be easier to do arbitrary computations on (possibly overlapping) chunks and then combine them in arbitrary ways. e.g. da.map_overlap(array, make_graph, depth=1, reduce_func=networkx.compose). That is, can we relax the assumption that map_blocks/map_overlap always produce array-likes? Here I am assuming that make_graph takes in arrays and produces networkx graphs. By default, reduce_func would be cropping + concatenating, along each axis in turn.

    Obviously I'm writing from a very naive perspective — I don't know much about the implementation internals — but that is the API I would expect. All of the above workarounds seem rather arcane!

  21. GenevieveBuckley commented on May 13, 2021

    @GenevieveBuckley
    ContributorAuthor

    John & I are going to have a chat about exactly this after the Dask summit - do you want to join us @jni? (We haven't picked a time yet, so I'm sure we can find one that suits you too)

  22. jni commented on May 13, 2021

    @jni
    Contributor

    I do!

  23. jsignell commented on May 13, 2021

    @jsignell
    Member

    Ooo I am very interested in thinking more about this as well, but I can read the discussion afterwards if timezones don't work out.

  24. Yu-AnChen commented on Aug 7, 2021

    @Yu-AnChen

    Thanks for the super helpful thread and the blog post! I needed some image mask operation and np.unique for each of my overlapping chunks. Following the example -

    Let's take this problem setup. I have a dask array, and a function foo. Function foo takes in an array chunk (or an array chunk with some overlap), computes something, and returns 1D results with a ragged length.

    import dask.array as da
    import numpy as np
    np.random.seed(0) # for reproducibility
    
    x = da.ones((100, 10), chunks=(10, 10))
    
    def foo(a):
        random_length = np.random.randint(1, 7)
        return np.arange(random_length)

    If we don't need any overlap, life is fine:

    result = da.map_blocks(foo, x, drop_axis=1)
    result.compute()  # this works
    
    array([0, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 0, 1, 2, 3, 0, 1, 2,
           3, 4, 5, 0, 1, 2, 0, 1, 2, 3, 4, 0])  # a good result

    But if we need some overlap for function foo to work correctly, then we run into problems:

    result = da.map_overlap(foo, x, depth=1, drop_axis=1)
    result.compute()  # incorrect output, because the result from foo is being trimmed
    
    array([1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1])  # the first and last element of the results from foo are being trimmed off before the whole thing is concatenated, which we don't want

    I expected that setting the keyword argument trim=False would avoid this problem, but instead we get an error:

    result = da.map_overlap(foo, x, depth=1, trim=False, drop_axis=1)
    result.compute()  # ValueError
    x = da.ones((100, 10), chunks=(10, 10))
    x_overlap = da.overlap.overlap(x, depth=1, boundary='none')
    
    result = x_overlap.map_blocks(foo, drop_axis=1).compute()
    # array([0, 1, 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 0, 1, 2, 0, 0, 1, 0, 1, 0, 1, 0, 1])
    
    np.sum(result == 0)
    # 10
    
    x.chunks
    # ((10, 10, 10, 10, 10, 10, 10, 10, 10, 10), (10,))
    
    x_overlap.chunks
    # ((11, 12, 12, 12, 12, 12, 12, 12, 12, 11), (10,))

    Would this be a reasonable solution for overlapping chunks? I assume it's not doubling the RAM usage by constructing the overlapping chunks first.

  25. GenevieveBuckley commented on Aug 9, 2021

    @GenevieveBuckley
    ContributorAuthor

    Would this be a reasonable solution for overlapping chunks? I assume it's not doubling the RAM usage by constructing the overlapping chunks first.

    Broadly yes, it seems like the easiest way to get around these problems is to

    1. Expand the array with dask.array.overlap.overlap to get an overlap around each chunk, then
    2. Run map_blocks on the expanded array

    I don't have a specific number to give you about RAM use. I didn't notice anything too out of the ordinary when I ran this. You might like to check this with your own work using the "worker memory" plot of the dask dashboard. Watching the dashboard is very helpful for getting an intuition about these things.

    If you do come close to your memory limit, I'd suggest:

    1. Carefully selecting your array chunk size, and...
    2. Taking a look at this video from Coiled on managing memory (particularly unmanaged memory) with Dask https://www.youtube.com/watch?v=nwR6iGR0mb0&t=25s
  26. Yu-AnChen commented on Aug 10, 2021

    @Yu-AnChen

    Thank you @GenevieveBuckley for the summary and the helpful tips! Looking forward to seeing future releases that would allow more flexibility in map_overlap outputs 😃

  27. jreniel commented on Jul 2, 2022

    @jreniel

    Hi All,
    Is there a way to make a meta for returning a geopandas.GeoDataFrame from map_{blocks/overlap} ?
    Most of my operation involve returning a non-array from each block, but I am struggling to make this work for returning arbitrary objects.
    I tried:
    meta = dd.utils.make_meta([('geometry', MultiPolygon)])
    but got:
    TypeError: dtype '<class 'shapely.geometry.multipolygon.MultiPolygon'>' not understood

    [EDIT]: Nevermind, I think I found the right place to ask, and also I think I found the answer. Thanks!

  28. GenevieveBuckley commented on Jul 5, 2022

    @GenevieveBuckley
    ContributorAuthor

    @jreniel perhaps you'd like to say what solution you ended up with? People with similar problems seem to be finding this thread, so it may help them to know what you did.

    We could also try to share the knowledge with a short blogpost. I wrote something here for arrays, having something sort of similar for dataframes could be useful. cc @jacobtomlinson - are you still looking for blogpost ideas?

  29. Yu-AnChen commented on Jul 5, 2022

    @Yu-AnChen

    @GenevieveBuckley A blog post on meta will be super helpful! The blog you wrote is a great reference for me as well.

    I've come to the following approach for handling arbitrary output (or no output at all, that I just leverage the side effect of the function) from each block that I'm trying to process in parallel -

    import dask
    import dask.array as da
    import numpy as np
    import dask.diagnostics
    
    # target array to be processed block-by-block
    # use `da.overlap.overlap` for overlapped blocks
    img_da = da.random.randint(
        low=1, high=10, size=(4, 4),
        dtype=int, chunks=2
    )
    
    # function that returns a python dictionary
    def max_arange(x):
        m = np.max(x)
        return {f"{m}": np.arange(m)}
    
    # list comprehension to iterate over the blocks, lazily
    delayed_result = [
        dask.delayed(max_arange)(b) 
        for b in img_da.blocks.ravel()
    ]
    
    # this is what I'm using for parallel processing, there's likely a better way to
    # do this
    result = dask.delayed(list)(delayed_result)
    result.visualize("mapped.png")
    with dask.diagnostics.ProgressBar():
        print(result.compute())

    Here are the print and exec graph

    [########################################] | 100% Completed |  0.1s
    [{'6': array([0, 1, 2, 3, 4, 5])}, {'7': array([0, 1, 2, 3, 4, 5, 6])}, {'7': array([0, 1, 2, 3, 4, 5, 6])}, {'6': array([0, 1, 2, 3, 4, 5])}]

    mapped

    I haven't done any careful benchmarking so you may want to monitor it in your use cases. Hope this approach is general enough for @jsignell 🙂

  30. jreniel commented on Jul 5, 2022

    @jreniel

    Hi @GenevieveBuckley, @Yu-AnChen and other interested readers,

    I have been writing Python code for about 6 years, but I've only recently started actively using Dask. So far I have had only partial success with dask, but I would like to give you more context around my experiments with dask, and how they relate to the problems I am trying to solve.

    The main problem I am trying to resolve is how to perform arbitrary operations over (geo) raster files of arbitrary size and resolutions. Here the main problem is that with or without dask, this might be, generally speaking, an intractable problem for modern machines. So we need to constraint both the data that we ingest, and many other parameters, to make it tractable and usable for numerical models.

    In the code excerpt below, the functions prefixed with an underscore represent the parts of my code are dedicated to make sure that the data that gets to a dask worker is already clean, those parts have been omitted for simplicity. In addition to that, I have included some comments of my observations about where things seem to go wrong, and how so.

    """Excerpt code for dask-delayed based geometry generation."""
    
    @delayed
    def build_multipolygon_from_raster_window(path, zmin, zmax, window):
    
        with rasterio.open(path) as src:     
            data = src.read(
                1,
                out_shape=(window.height, window.width),
                window=window,
                )
    
        x0, y0, x1, y1 = array_bounds(
            window.height,
            window.width,
            rasterio.windows.transform(window, transform)
        )
           
        x = np.linspace(x0, x1, window.width)
        y = np.linspace(y1, y0, window.height)
    
        fig, ax = plt.subplots()
        return _get_multipolygon_from_axes(ax.contourf(x, y, data, levels=[zmin, zmax]))
    
    
    async def main():
    
        from dask.distributed import Client
    
        config = _get_user_config_obj()
    
        # Iterate over each raster path, and user config requirements, pass those to @delayed
        multipolygons = []
        for path, user_opts in _iter_requests(config):
            multipolygons.extend([
                build_multipolygon_from_raster_window(path, user_opts.zmin, user_opts.zmax, raster_window)
                # uses a custom window generation, because the default dask-array blocks may be too small,
                # or maybe it's just lack of experience using dask.Array blocks?
                for raster_window in _iter_raster_windows(path, user_opts)
                ])
    
        # get user defined cluster args
        cluster_kwargs = config.cluster.kwargs.copy()
    
        start = time()
        async with config.cluster.Cluster(**cluster_kwargs) as cluster:
    
            # This sometimes triggers shut down workers that don't have promised keys
            # see: https://dask.discourse.group/t/scale-1-fails-shut-down-workers-that-dont-have-promised-keys/872
            if config.cluster.scale is not None:
                cluster.scale(config.cluster.scale)
            if config.cluster.adapt is not None:
                cluster.adapt(**config.cluster.adapt)
            async with Client(
                cluster,
                asynchronous=True,
                ) as client:
                logger.info(f'{cluster.dashboard_link}')
    
                # when the list is very long, Nanny's fail to start with time outs (semi-random)
                # Additionally, if the list is very long, but the Nanny's do start, sometimes it gets
                # stuck in a loop going from 100% back to ~60%, rinse and repeat, I noticed it while
                # looking at the dashbord
                gdf = gpd.GeoDataFrame([{'geometry': geometry} for geometry in await client.gather(client.compute(multipolygons, dtype=MultiPolygon)) if not geometry.is_empty])
    
                # .... do some more stuff with client.compute which also has they own additional nuances ... 
                
        gdf.plot() # ...
    
    
    if __name__ == "__main__":
        asyncio.run(main())

    In addition to these observations, there's another critical point that dask doesn't seem to support at the moment. In particular I need to submit a delayed function that uses multiprocessing.Pool internally, but that doesn't work because I get an error: AssertionError: daemonic processes are not allowed to have children. From my understanding, this happens when a multiprocessing.Pool worker tries to initialize it's own multiprocessing.Pool internally, and therefore, a child processes in dask cannot fork. I understand the logic behind this, and there are ways to "cheat" by calling multithreaded compiled code, but if you don't set this up correctly, you might end up oversubscribing your nodes with probable node locking.

    Because of this, I find that my code has to generate it's own job submission but that sounds awfully innefficient, considering that dask_jobqueue already does the heavy lifting for you. So what I was considering is, if we could somehow replace the call to dask-worker in the job sumission file with a custom Python function, then we can use multithreaded-distributed computing using dask. The problem is that I don't think dask_jobqueue supports this, so I am trying to see if I can leverage some of the dask tools to be able to launch and supervise my own custom job scripts... Any ideas?

    And finally, sorry for the long post. Dask seems very promising, but at the same time, it seems that it doesn't solve all of myt requirememts at the time. But it also seems that it could solve them, or maybe it's just ignorance from my part. All in all I think it's a great tool worth exploring, and I have too many questions in my head, and I am a bit overwhelmed with all of this information, but I hope I will be able to sort it out over time.

    Any comments, ideas, suggestions or collaboration attempts are welcome, I am just trying to finish my PhD, but also create something memorable.

    Thanks!
    -Jaime

  31. GenevieveBuckley commented on Jul 6, 2022

    @GenevieveBuckley
    ContributorAuthor

    Thank you for the example, and the extra context @jreniel 😄

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions