Repository navigation
Description
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
GenevieveBuckley commentedon Apr 22, 2021
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
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
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'GenevieveBuckley commentedon Apr 22, 2021
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
chrisroat commentedon Apr 22, 2021
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.chrisroat commentedon Apr 22, 2021
And for completeness, here's how to do it with arrays:
chrisroat commentedon Apr 22, 2021
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.
GenevieveBuckley commentedon Apr 22, 2021
Yes, this is true.
The reason for raising this issue is:
chrisroat commentedon Apr 22, 2021
Agree that it is useful! I have used examples of this in my work. A unified
metaargument, which could be either an array or dataframe, could be a usable interface.jsignell commentedon Apr 22, 2021
You can use the
drop_axisto alter the dimensionality of the output. For example in your case above you can do:It's not clear to me from your original problem statement? Are you looking for the output to be 1D?
chrisroat commentedon Apr 22, 2021
jsignell commentedon Apr 22, 2021
Ah ok like this?
Note that the chunks kwarg is only required if you want the
result.chunksandresult.sizeto be accurate.result.compute()will work fine without it.jsignell commentedon Apr 22, 2021
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.
chrisroat commentedon Apr 22, 2021
jsignell commentedon Apr 26, 2021
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_delayedstep.chrisroat commentedon Apr 26, 2021
That sounds like a similar approach, but I'm not sure how one avoids
to_delayedordask.delayed. How can one convert each chunk to a bag without going through something delayed?GenevieveBuckley commentedon Apr 27, 2021
Thanks @chrisroat and @jsignell, it's really great to see these other examples.
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.
8 remaining items
GenevieveBuckley commentedon May 3, 2021
@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)
chrisroat commentedon May 3, 2021
Can you try adding the meta parameter? I see that my original example didn't include that -- I've updated it.
GenevieveBuckley commentedon May 4, 2021
Ah, much better now! Thanks @chrisroat
jni commentedon May 12, 2021
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 thatmake_graphtakes in arrays and produces networkx graphs. By default,reduce_funcwould 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!
GenevieveBuckley commentedon May 13, 2021
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)
jni commentedon May 13, 2021
I do!
jsignell commentedon May 13, 2021
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.
Yu-AnChen commentedon Aug 7, 2021
Thanks for the super helpful thread and the blog post! I needed some image mask operation and
np.uniquefor each of my overlapping chunks. Following the example -Would this be a reasonable solution for overlapping chunks? I assume it's not doubling the RAM usage by constructing the overlapping chunks first.
GenevieveBuckley commentedon Aug 9, 2021
Broadly yes, it seems like the easiest way to get around these problems is to
dask.array.overlap.overlapto get an overlap around each chunk, thenmap_blockson the expanded arrayI 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:
Yu-AnChen commentedon Aug 10, 2021
Thank you @GenevieveBuckley for the summary and the helpful tips! Looking forward to seeing future releases that would allow more flexibility in
map_overlapoutputs 😃jreniel commentedon Jul 2, 2022
Hi All,
Is there a way to make a meta for returning a
geopandas.GeoDataFramefrommap_{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!
GenevieveBuckley commentedon Jul 5, 2022
@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?
Yu-AnChen commentedon Jul 5, 2022
@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 -
Here are the print and exec graph
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 🙂
jreniel commentedon Jul 5, 2022
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.
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.Poolinternally, 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 amultiprocessing.Poolworker tries to initialize it's ownmultiprocessing.Poolinternally, 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_jobqueuealready does the heavy lifting for you. So what I was considering is, if we could somehow replace the call todask-workerin 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 thinkdask_jobqueuesupports 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
GenevieveBuckley commentedon Jul 6, 2022
Thank you for the example, and the extra context @jreniel 😄