Skip to content

[Data] Vectorize ValueCounter column combination via VectorizedAggregateFnV2 - #67664

Open
deep1blue wants to merge 5 commits into
ray-project:masterfrom
deep1blue:perf/ray-data-value-counter-vectorized-combine
Open

deep1blue wants to merge 5 commits into
ray-project:masterfrom
deep1blue:perf/ray-data-value-counter-vectorized-combine

Conversation

@deep1blue

Copy link
Copy Markdown
Contributor

Why are these changes needed?

ValueCounter in python/ray/data/aggregate.py previously inherited from AggregateFnV2, so TableBlockAccessor._combine_column fell back to _fold_accumulator_column and folded partial block accumulators pairwise via ValueCounter.combine().

On every pairwise combine(current_accumulator, new_accumulator) call, ValueCounter rebuilt value_to_index = {v: i for i, v in enumerate(values)} from scratch over the accumulated values list:

# Build a value → index map once (avoid repeated lookups)
value_to_index = {v: i for i, v in enumerate(values)}

When combining $B$ partial accumulators with $U$ unique values, rebuilding value_to_index on every step resulted in $O(B \cdot U)$ dictionary reconstructions across blocks.

This PR makes ValueCounter subclass VectorizedAggregateFnV2[Dict[str, List], Dict[str, List]] and implements _combine_column(self, accumulator_col: BlockColumn) to build and maintain value_to_index once across the entire column of partial accumulators in $O(\sum_b |acc_b|)$ linear time, while preserving combine() for direct callers, exact first-seen value ordering, and None/empty-column semantics.

Benchmark

Combining 800 partial block accumulators (1,000 distinct values per block, 100,000 total distinct values):

  • Before (_fold_accumulator_column pairwise combine): 119.99 s
  • After (ValueCounter._combine_column): 0.79 s (151.9x speedup)

Community Credit & Acknowledgments

Related issue number

N/A

Checks

…ateFnV2

ValueCounter previously inherited from AggregateFnV2 and folded partial
block accumulators pairwise via _fold_accumulator_column. Each pairwise
combine() call rebuilt value_to_index = {v: i for i, v in enumerate(values)}
from scratch over the growing accumulator, resulting in O(B * U) dictionary
rebuilds across B partial blocks and U unique values.

Make ValueCounter inherit from VectorizedAggregateFnV2 and implement
_combine_column to maintain a single value_to_index dictionary across all
partial accumulators in the column in O(sum_b |acc_b|) time while keeping
combine() for direct callers and preserving first-seen value ordering and
null-handling semantics.

Signed-off-by: Parth Vadera <[email protected]>
@deep1blue
deep1blue requested a review from a team as a code owner November 1, 2026 00:54

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request updates the ValueCounter aggregation class to inherit from VectorizedAggregateFnV2 and implements the _combine_column method to optimize column-wise combining of accumulators. It also adds comprehensive unit tests to verify the correctness, recombinability, and null-handling of this new method. The review feedback highlights a critical issue regarding NaN handling and unhashable types in the dictionary lookups within _combine_column, suggesting the use of _to_hashable and canonicalizing NaN values to np.nan. Additionally, it recommends adding a unit test to cover this NaN canonicalization behavior.

Comment on lines +1484 to +1491
for v_new, c_new in zip(accumulator["values"], accumulator["counts"]):
idx = value_to_index.get(v_new)
if idx is not None:
counts[idx] += c_new
else:
value_to_index[v_new] = len(values)
values.append(v_new)
counts.append(c_new)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

In Python, different NaN float instances do not compare equal (float('nan') == float('nan') is False), which can cause duplicate NaN entries in the combined accumulator when merging multiple blocks. Additionally, list-like values (e.g., lists or numpy arrays) are unhashable and will raise a TypeError when used as dictionary keys.\n\nTo ensure correctness and robustness, we should normalize the values using _to_hashable and canonicalize NaN values to the singleton np.nan before performing dictionary lookups and insertions.

            for v_new, c_new in zip(accumulator[\"values\"], accumulator[\"counts\"]):\n                v_norm = _to_hashable(v_new)\n                if isinstance(v_norm, float) and np.isnan(v_norm):\n                    v_norm = np.nan\n                idx = value_to_index.get(v_norm)\n                if idx is not None:\n                    counts[idx] += c_new\n                else:\n                    value_to_index[v_norm] = len(values)\n                    values.append(v_norm)\n                    counts.append(c_new)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 54c7d05: _to_hashable now canonicalizes float NaN instances (v != v) to np.nan and handles both list and np.ndarray inputs consistently across combine and _combine_column.

Comment on lines +1004 to +1017
all_null_col = pa.chunked_array(
[
pa.array(
[None, None],
type=pa.struct(
[
("values", pa.list_(pa.string())),
("counts", pa.list_(pa.int64())),
]
),
)
]
)
assert agg._combine_column(all_null_col) is None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Add a unit test to verify that ValueCounter._combine_column correctly canonicalizes different NaN float instances and combines them into a single count.

        all_null_col = pa.chunked_array(\n            [\n                pa.array(\n                    [None, None],\n                    type=pa.struct(\n                        [\n                            (\"values\", pa.list_(pa.string())),\n                            (\"counts\", pa.list_(pa.int64())),\n                        ]\n                    ),\n                )\n            ]\n        )\n        assert agg._combine_column(all_null_col) is None\n\n    def test_value_counter_combine_column_nan(self):\n        agg = ValueCounter(on=\"v\")\n        blocks = [\n            pa.table({\"v\": [np.nan, \"a\", \"a\"]}),\n            pa.table({\"v\": [float(\"nan\"), \"b\"]}),\n        ]\n        partials = [agg.aggregate_block(block) for block in blocks]\n        combined = agg._combine_column(self._accumulator_column(partials))\n        assert self._as_counts(combined) == {np.nan: 2, \"a\": 2, \"b\": 1}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added NaN float canonicalization test coverage in test_value_counter_combine_column_unit in 54c7d05.

@ray-gardener ray-gardener Bot added performance data Ray Data-related issues community-contribution Contributed by the community labels Nov 1, 2026
deep1blue and others added 2 commits November 1, 2026 01:40
…._combine_column

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
Co-authored-by: Copilot <[email protected]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 17, 2026
@deep1blue

Copy link
Copy Markdown
Contributor Author

Keeping this PR active — all review feedback has been addressed and unit tests are passing. Ready for maintainer review whenever convenient.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 17, 2026
@abhishekverma-ray abhishekverma-ray added the go add ONLY when ready to merge, run all tests label Nov 18, 2026

@abhishekverma-ray abhishekverma-ray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The code looks sound. Combining partial results again gives the same answer, and the NaN dedup across partial results is a real improvement. On tests:

  • The four test_value_counter_combine_column_* tests call the private _combine_column and mostly copy the TopKUnique combine tests. Could the existing ones be parametrized over the aggregator?
  • The empty / all-null case passes on master.
  • The list half of the NaN test builds accumulators that value_counts can't produce.
  • Keep test_value_counter_end_to_end_and_groupby, but set shuffle_input_batch_bytes = 0 and spread each group's values across many blocks, like test_topk_unique_groupby_many_groups_and_blocks. Otherwise small data collapses to one partial result per group, and the merge path never runs.
  • Please add a public-API case with NaN rows across 2+ blocks, asserting a single NaN entry.

…roupby via public API

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
@deep1blue

Copy link
Copy Markdown
Contributor Author

Thanks @abhishekverma-ray! Updated 28897bffc5:

  • Removed the parallel TestValueCounter class and parametrized test_topk_unique_combine_column_matches_pairwise_combine and test_topk_unique_combine_column_is_recombinable over (TopKUnique, ValueCounter).
  • Added test_value_counter_groupby_and_nan with shuffle_input_batch_bytes = 0 and NaN values spread across two blocks, exercising ds.aggregate(ValueCounter(on="v")) and ds.groupby("g").aggregate(ValueCounter(on="v")) through the public API.

Verified locally with pytest python/ray/data/tests/test_aggregations.py -k "test_topk_unique_combine_column_matches_pairwise_combine or test_topk_unique_combine_column_is_recombinable or test_value_counter_groupby_and_nan" (7 passed).

Move ValueCounter._combine_column above ValueCounter.combine so it merges
cleanly alongside ValueCounter._arrow_agg_spec added on master (ray-project#68202).

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
goutamvenkat-anyscale added a commit that referenced this pull request Nov 25, 2026
> Stacked on #68259. Review that one first.

## Summary

`ValueCounter` returns different results for the same data depending on
whether a block is Arrow- or pandas-backed. `pd.Series.value_counts()`
drops nulls, while Arrow's `value_counts` counts them:

```python
vals = ["a", None, "b", "a"]
arrow  -> {'values': ['a', None, 'b'], 'counts': [2, 1, 1]}
pandas -> {'values': ['a', 'b'],       'counts': [2, 1]}
```

Users don't choose a block's format; it depends on upstream operators
and `batch_format`. So today, adding a `map_batches(...,
batch_format="pandas")` upstream silently changes the counts. This PR
makes the pandas path match Arrow, which is the behavior #68202
specifies in `value_counter_spec()`.

## Changes

- `PandasBlockColumnAccessor.value_counts` now counts nulls. It also
normalizes `pd.NA`, `NaN` and `None` to a single `None` key. Without
that, `ValueCounter.combine` wouldn't merge them with Arrow's `None`
across blocks, and `NaN` wouldn't reliably merge with itself.
- The null check is a new local `_is_scalar_null`, because
`util.is_null` misses `pd.NA`/`pd.NaT`. Widening `is_null` would also
change every aggregation's null-safety wrappers, so that's left for a
separate change. (`aggregate.py`'s null-stripping loop has the same gap
today.)
- A stale comment in `aggregate.py` that said pandas drops nulls is
updated. The accounting it describes stays correct.

## Tests

Adds `test_block_column_accessor_properties.py`, which uses `hypothesis`
from #68259. Its properties:
- Arrow and pandas agree, across the pandas dtypes Ray Data produces
(`int64[pyarrow]`, nullable `Int64`/`string`, numpy). This fails on the
parent commit and passes here.
- Counts sum to the row count.
- A regression guard for `sum`/`min`/`max`/`mean`/`count`.

```
pytest python/ray/data/tests/unit/        -> 2997 passed, 208 skipped
pytest python/ray/data/tests/unit/test_block_column_accessor_properties.py \
       python/ray/data/tests/unit/test_transform_pyarrow_properties.py  -> 7 passed
```

`pre-commit run` passes on all changed files.

## Not a duplicate

No open PR changes `PandasBlockColumnAccessor.value_counts`. #68202 and
#67664 touch `ValueCounter` on the Arrow/vectorized path, not the pandas
accessor. This change is complementary.

**Subsystems:** Block / data format; Shuffle / aggregation

AI assistance was used for this change. Property-based testing across
the two `BlockColumnAccessor` implementations found the divergence.

---------

Signed-off-by: Goutam <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests performance unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants