Repository navigation
Conversation
…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]>
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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)There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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}There was a problem hiding this comment.
Added NaN float canonicalization test coverage in test_value_counter_combine_column_unit in 54c7d05.
…._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]>
|
This pull request has been automatically marked as stale because it has not had 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. |
|
Keeping this PR active — all review feedback has been addressed and unit tests are passing. Ready for maintainer review whenever convenient. |
abhishekverma-ray
left a comment
There was a problem hiding this comment.
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_columnand mostly copy theTopKUniquecombine 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_countscan't produce. - Keep
test_value_counter_end_to_end_and_groupby, but setshuffle_input_batch_bytes = 0and spread each group's values across many blocks, liketest_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]>
|
Thanks @abhishekverma-ray! Updated
Verified locally with |
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]>
> 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]>
Why are these changes needed?
ValueCounterinpython/ray/data/aggregate.pypreviously inherited fromAggregateFnV2, soTableBlockAccessor._combine_columnfell back to_fold_accumulator_columnand folded partial block accumulators pairwise viaValueCounter.combine().On every pairwise
combine(current_accumulator, new_accumulator)call,ValueCounterrebuiltvalue_to_index = {v: i for i, v in enumerate(values)}from scratch over the accumulatedvalueslist:When combining$B$ partial accumulators with $U$ unique values, rebuilding $O(B \cdot U)$ dictionary reconstructions across blocks.
value_to_indexon every step resulted inThis PR makes$O(\sum_b |acc_b|)$ linear time, while preserving
ValueCountersubclassVectorizedAggregateFnV2[Dict[str, List], Dict[str, List]]and implements_combine_column(self, accumulator_col: BlockColumn)to build and maintainvalue_to_indexonce across the entire column of partial accumulators incombine()for direct callers, exact first-seen value ordering, andNone/empty-column semantics.Benchmark
Combining 800 partial block accumulators (
1,000distinct values per block,100,000total distinct values):_fold_accumulator_columnpairwisecombine):119.99 sValueCounter._combine_column):0.79 s(151.9x speedup)Community Credit & Acknowledgments
VectorizedAggregateFnV2._combine_columnarchitecture andValueCounterdesign.Related issue number
N/A
Checks
git commit -s) in this PR.scripts/format.shto lint the changes in this PR.pytest python/ray/data/tests/test_aggregations.py -k TestValueCounter -v)