Skip to content

Optimized groupby aggregations when grouping by a sorted index #8361

Open

Description

@gjoseph92

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

  1. jsignell commented on Nov 9, 2021

    @jsignell
    Member

    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.

  2. gjoseph92 commented on Nov 9, 2021

    @gjoseph92
    CollaboratorAuthor

    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

  3. dcherian commented on Nov 17, 2021

    @dcherian
    Collaborator

    👍 I implemented this for dask.array in flox as method="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 blockwise or _tree_reduce as 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!

    I agree that there's a lot of room to improve groupby performance, and a fair amount of it is pretty low-hanging.

    Curious to hear what these ideas are!

  4. gjoseph92 commented on Nov 30, 2021

    @gjoseph92
    CollaboratorAuthor

    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!

  5. DahnJ commented on Nov 30, 2021

    @DahnJ
    Contributor

    Sadly, it sounds like you ran into this exact issue. Good to get more validation that this is worth fixing!

    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 groupby using map_partitions at first is that it felt like I'm somehow circumventing Dask and doing something hacky and possibly wrong.

    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.

    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_index put a single index into multiple partitions?. It would be good to have a canonical answer to that question, too.

  6. gjoseph92 commented on Dec 1, 2021

    @gjoseph92
    CollaboratorAuthor

    I also wonder just how many users' workflows are failing because of this precise issue.

    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.

    the reason why I didn't even think of mapping groupby using map_partitions at first is that it felt like I'm somehow circumventing Dask and doing something hacky and possibly wrong.

    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!

    Here is a related SO question

    That was a good question. I replied to it; this is a bug: #8437.

  7. jsignell commented on Dec 1, 2021

    @jsignell
    Member

    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

    df = self.obj
    should_shuffle = not (
    df.known_divisions and df._contains_index_name(self.index)
    )
    if should_shuffle:
    df2, index = self._shuffle(meta)
    else:
    df2 = df
    index = self.index
    # Perform embarrassingly parallel groupby-apply
    kwargs["meta"] = meta
    df3 = map_partitions(
    _groupby_slice_apply,
    df2,
    index,
    self._slice,
    func,
    token=funcname(func),
    *args,
    group_keys=self.group_keys,
    **self.observed,
    **self.dropna,
    **kwargs,
    )

  8. gjoseph92 commented on Dec 1, 2021

    @gjoseph92
    CollaboratorAuthor

    ^ yes, this is exactly it!

  9. jsignell commented on Dec 2, 2021

    @jsignell
    Member

    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 first as a map_partitions with no groupby per-chunk, but the implementation of df.first is different than the implementation of groupby.first so 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?

  10. gjoseph92 commented on Dec 2, 2021

    @gjoseph92
    CollaboratorAuthor

    we still need to do a groupby per-chunk

    This is definitely true. But to me, it's very cheap. Sorry I didn't make that clear!

    I'm not quite sure I see a big opportunity for optimization here. Am I missing something?

    Skipping a full aca is 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.

    we might occassionally need to aggregate across results (for the case of duplicate divisions)

    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:

    1. It's rare to have duplicate divisions at all
    2. When there are duplicate divisions, the number of duplicates compared to the number of non-duplicates is small
    3. When there are duplicate divisions, the length of each consecutive run is short compared to the total number of divisions

    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 getting aca'd.

  11. jsignell commented on Dec 2, 2021

    @jsignell
    Member

    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.

  12. added
    needs attention
    on Sep 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

dataframeneeds attention

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions