Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX-#3571: fallback to 'sort=True' on categorical keys in groupby #3715

Merged
merged 2 commits into from
Nov 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions modin/core/dataframe/algebra/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from .map_reduce import MapReduce
from .default2pandas.groupby import GroupBy
from modin.utils import try_cast_to_pandas, hashable
from modin.error_message import ErrorMessage


class GroupByReduce(MapReduce):
Expand Down Expand Up @@ -290,6 +291,21 @@ def caller(
)
assert axis == 0, "Can only groupby reduce with axis=0"

# The bug only occurs in the case of Categorical 'by', so we might want to check whether any of
# the 'by' dtypes is Categorical before going into this branch, however triggering 'dtypes'
# computation if they're not computed may take time, so we don't do it
Comment on lines +294 to +296
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

modin_frame._dtypes attribute is None most of the time, its computation requires calling MapReduce and actual data materialization. I don't think we want to trigger this on every groupby(sort=False)

if not groupby_args.get("sort", True) and isinstance(by, type(query_compiler)):
ErrorMessage.missmatch_with_pandas(
operation="df.groupby(categorical_by, sort=False)",
message=(
"the groupby keys will be sorted anyway, although the 'sort=False' was passed. "
"See the following issue for more details: "
"https://github.com/modin-project/modin/issues/3571"
),
)
groupby_args = groupby_args.copy()
RehanSD marked this conversation as resolved.
Show resolved Hide resolved
groupby_args["sort"] = True

if numeric_only:
qc = query_compiler.getitem_column_array(
query_compiler._modin_frame.numeric_columns(True)
Expand Down
2 changes: 1 addition & 1 deletion modin/pandas/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2894,7 +2894,7 @@ def value_counts(
):
if subset is None:
subset = self._query_compiler.columns
counted_values = self.groupby(by=subset, sort=False, dropna=dropna).size()
counted_values = self.groupby(by=subset, dropna=dropna, observed=True).size()
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. sort=False -> sort=True so the users won't see the warning thrown by groupby
  2. observed=False -> observed=True because newly added tests for DataFrame.value_counts showed that it's have to be set (see the example):
Example
>>> df = pandas.DataFrame({"a": [1, 1, 2, 2], "b": [2, 2, 3, 3]}, dtype="category")
>>> df
   a  b
0  1  2
1  1  2
2  2  3
3  2  3
>>> df.value_counts()
a  b
1  2    2
2  3    2
dtype: int64
>>> df.groupby(["a", "b"]).size()
a  b
1  2    2
   3    0
2  2    0
   3    2
dtype: int64
>>> df.groupby(["a", "b"], observed=True).size()
a  b
1  2    2
2  3    2
dtype: int64

if sort:
counted_values.sort_values(ascending=ascending, inplace=True)
if normalize:
Expand Down
12 changes: 12 additions & 0 deletions modin/pandas/test/dataframe/test_reduction.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,3 +408,15 @@ def comparator(md_res, pd_res):
# visit modin-issue#3388 for more info.
check_exception_type=None if sort and ascending is None else True,
)


def test_value_counts_categorical():
# from issue #3571
data = np.array(["a"] * 50000 + ["b"] * 10000 + ["c"] * 1000)
random_state = np.random.RandomState(seed=42)
random_state.shuffle(data)

eval_general(
*create_test_dfs({"col1": data, "col2": data}, dtype="category"),
lambda df: df.value_counts(),
)
26 changes: 26 additions & 0 deletions modin/pandas/test/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1731,6 +1731,32 @@ def test_not_str_by(by, as_index):
eval_general(md_grp, pd_grp, lambda grp: grp.first())


@pytest.mark.parametrize("sort", [True, False])
@pytest.mark.parametrize("is_categorical_by", [True, False])
def test_groupby_sort(sort, is_categorical_by):
# from issue #3571
by = np.array(["a"] * 50000 + ["b"] * 10000 + ["c"] * 1000)
random_state = np.random.RandomState(seed=42)
random_state.shuffle(by)
Comment on lines +1738 to +1740
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the bug is partitioning dependent, that's why I'm carrying the same data all around

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To clarify - you mean the shuffle is in place so that the bug gets tripped (bc if we didn't shuffle and the values weren't replicated across the partitions, we wouldn't hit the bug?)

Copy link
Collaborator Author

@dchigarev dchigarev Nov 20, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. For this data shuffled with this specific seed we know for sure that there is a problem caused by the incorrect order of categories in the reduce phase of groupby (see the issue explanation).

This problem might not be visible when the values are in a different order, so I'm using exact data from the #3571 report as a solid reproducer of the issue.


data = {"key_col": by, "data_col": np.arange(len(by))}
md_df, pd_df = create_test_dfs(data)

if is_categorical_by:
md_df = md_df.astype({"key_col": "category"})
pd_df = pd_df.astype({"key_col": "category"})

md_grp = md_df.groupby("key_col", sort=sort)
pd_grp = pd_df.groupby("key_col", sort=sort)

modin_groupby_equals_pandas(md_grp, pd_grp)
eval_general(md_grp, pd_grp, lambda grp: grp.sum())
eval_general(md_grp, pd_grp, lambda grp: grp.size())
eval_general(md_grp, pd_grp, lambda grp: grp.agg(lambda df: df.mean()))
eval_general(md_grp, pd_grp, lambda grp: grp.dtypes)
eval_general(md_grp, pd_grp, lambda grp: grp.first())


def test_sum_with_level():
data = {
"A": ["0.0", "1.0", "2.0", "3.0", "4.0"],
Expand Down
12 changes: 12 additions & 0 deletions modin/pandas/test/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -3439,6 +3439,18 @@ def sort_sensitive_comparator(df1, df2):
)


def test_value_counts_categorical():
# from issue #3571
data = np.array(["a"] * 50000 + ["b"] * 10000 + ["c"] * 1000)
random_state = np.random.RandomState(seed=42)
random_state.shuffle(data)

eval_general(
*create_test_series(data, dtype="category"),
lambda df: df.value_counts(),
)


@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_values(data):
modin_series, pandas_series = create_test_series(data)
Expand Down