Repository navigation
Description
Similar request to #2999
When grouping by the index, and the index has known divisions, most aggregations could be a simple map_partitions. Since each partition already contains all the values for an output group[^1], there's no need to exchange data between partitions.
However in these cases, we still do apply_concat_apply, _cum_agg, etc. and generate complex graphs that involve a lot of data transfer.
In normal pandas use, I'm not sure how common it is to groupby the index versus a column. However, in dask, using the known divisions of the index is highly recommended (see best practices) and something users should try to do, especially with large datasets. In particular, once shuffling performs better (xref dask/distributed#5435), a pattern of doing one set_index up front (or using a partitioned data format like Parquet) and then many fast operations on that should be effective.
I'd want something like this to involve minimal data transfer after the set_index step:
import dask.dataframe as dd
df = dd.read_parquet(...)
# a savvy user recognizes this is worthwhile since there are multiple date ops to do next
df_by_day = df.set_index("date")
daily_users = df_by_day.groupby(["date", "user_id"]).count()
daily_sales = df_by_day.groupby(["date", "sale_amt"]).sum()
daily_summary = daily_counts.merge(daily_sales, on="date")
# ^ this should be fast since both groupbys have retained their `divisions`Someday, it might be nice if users didn't even have to do the set_index, and we had an optimization that could recognize that multiple groupbys would benefit from a pre-shuffle and insert one automatically. However, that's a hard optimization to implement (might require HLEs #7933) and a ways off. Getting users to understand that they should use set_index more carefully than in pandas, and its importance as a performance tool, seems easier. As we do that, let's make sure we're taking as much advantage of it as possible.
[^1] When all the rows in a partition have the same index value, then you do need to combine partitions. For example: in divisions=[0, 1, 2, 2, 4, 5], the partitions containing 1-2, 2-2, and 2-4 would need to be combined, probably using the normal apply_concat_apply logic. However, since we know the divisions, we can be more selective about where we do this and reduce some transfer. With well-balanced partitions, this should be a relatively rare case, and there usually shouldn't be more than a handful of consecutive partitions with the same value.
Activity
jsignell commentedon Nov 9, 2021
YES! I am very excited about this idea. In general, there are a lot of opportunities for doing things better in groupby. I think the current implementations are written more for legibility and generalizability and less for performance.
Let me know if you are actively planning on working on this or would like to talk things through.
gjoseph92 commentedon Nov 9, 2021
Awesome! I'm excited about it too. I agree that there's a lot of room to improve groupby performance, and a fair amount of it is pretty low-hanging.
I'm not actively planning on working on this right now, and I'm not sure if anyone else is either. I think we should though! Issues with groupby performance and usability are the top things I hear from users right now.
cc @jrbourbeau @fjetter @jcrist
dcherian commentedon Nov 17, 2021
👍 I implemented this for
dask.arrayin flox asmethod="cohorts".I implemented it by indexing out "cohorts" or "groups that occur together" (which is another groupby operation hah) and then either applying the grouped reduction using either
blockwiseor_tree_reduceas appropriate for each subset. Then concatenate those results to form the final result.I learned about the possible blockwise optimization from this post so thank you!
Curious to hear what these ideas are!
gjoseph92 commentedon Nov 30, 2021
Hey @DahnJ, really enjoyed your blog post (https://targomo.medium.com/how-we-learned-to-love-dask-and-achieved-a-40x-speedup-aa14e72d99c0#fa71). Sadly, it sounds like you ran into this exact issue. Good to get more validation that this is worth fixing!
DahnJ commentedon Nov 30, 2021
Yes, improving this makes a lot of sense to me! I also wonder just how many users' workflows are failing because of this precise issue. I did hear that "what I do is embarrassingly parallelizable, so why do I always resort to looping over chunks of data" sentiment a number of times at the summit, possibly suggesting Dask introduces some unexpected dependency between partitions.
On the API side, the reason why I didn't even think of mapping
groupbyusingmap_partitionsat first is that it felt like I'm somehow circumventing Dask and doing something hacky and possibly wrong.If I understand correctly, you're suggesting that the same index could actually be present in multiple partitions? Empirically, I've actually never seen that happen, even when it would make sense in terms of balancing the partitions. Here is a related SO question: Dask dataframe: Can
set_indexput a single index into multiple partitions?. It would be good to have a canonical answer to that question, too.gjoseph92 commentedon Dec 1, 2021
Agreed. I think this should be one of the top priority DataFrame issues to work on. I was honestly shocked when I read the code and realized we weren't utilizing the sorted index.
This is usually the right way to feel. It's very reasonable that you'd expect Dask to be doing the obvious, correct thing here with groupby!
That was a good question. I replied to it; this is a bug: #8437.
jsignell commentedon Dec 1, 2021
Ok so I think we already do this check for whether or not we need to do anything special in
apply. We could just extend that logic:dask/dask/dataframe/groupby.py
Lines 1692 to 1717 in a5aecac
gjoseph92 commentedon Dec 1, 2021
^ yes, this is exactly it!
jsignell commentedon Dec 2, 2021
I did some initial investigation and I think that we still need to do a groupby per-chunk. Otherwise we would need to reimplement all the groupby methods to act on non groupby objects. As an experiment I tried implementing just
firstas a map_partitions with no groupby per-chunk, but the implementation ofdf.firstis different than the implementation ofgroupby.firstso it didn't work quite how I had hoped. So if we need to do a groupby per-chunk and we might occassionally need to aggregate across results (for the case of duplicate divisions), I'm not quite sure I see a big opportunity for optimization here. Am I missing something?gjoseph92 commentedon Dec 2, 2021
This is definitely true. But to me, it's very cheap. Sorry I didn't make that clear!
Skipping a full
acais huge win (see the graphs in the blog post for an example). It avoids needlessly doing a tree-reduction and concatenating all those partitions, which saves a ton of data transfer, of tasks, and of memory from all the concatenations.I think we should error on this case for now since it's probably invalid at the moment (#8437). But even when we do support it, I'd expect that typically:
Which if true, means that for a DataFrame of say, 1,000 partitions, we'd have maybe 10-100 partitions getting
aca'd (with multiple shallower trees), instead of all 1,000 gettingaca'd.jsignell commentedon Dec 2, 2021
Ok that makes sense. I can see how fewer layers is good even if the total number of tasks does not decrease by much. I'll keep pushing on it.