Repository navigation
[Data] Vectorize AbsMax, Std, AsList, Quantile, ValueCounter, TopKUnique; add raw_to_partial hook - #68202
Conversation
…ity keys in SHUFFLE_V2 Probe the first N rows of each map block; if the key-unique ratio exceeds a threshold, ship raw (column-pruned) rows instead of partial state. The reducer projects raw rows into partial state per row (raw_to_state) and merges everything in a single group_by. Gated behind DataContext.enable_adaptive_partial_aggregation (off by default). Signed-off-by: sampan <[email protected]>
…y selection - Turn enable_adaptive_partial_aggregation on by default (release benchmark: ~17% faster on the 7M-group SF1000 groupby, no change at 84 groups). - Accept partial_aggregation_mode="probe" and honor the configured probe size and threshold when it is forced. - Drop the unused _estimate_key_unique_ratio planning hook. - Rename ArrowAggSpec.raw_to_state to raw_to_partial. Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
Map tasks only ship raw rows when every agg can project them into partial state, so the reducer no longer needs a two-pass fallback. Signed-off-by: sampan <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces adaptive map-side partial aggregation for SHUFFLE_V2 hash aggregations in Ray Data, allowing map tasks to skip pre-aggregation when key cardinality is high and instead ship raw rows to be converted on the reducer. It implements raw_to_partial across various vectorized aggregations (such as Mean, Std, Quantile, and TopKUnique) and adds a probing policy to dynamically decide when to skip pre-aggregation. The review feedback highlights two valuable improvements: optimizing the integer type selection in _narrow_ids to maximize the use of faster radix sorts, and preventing NaN propagation and warnings in _merge_std by safely computing delta only for active rows.
…nt partial-agg flag Map tasks used to decide whether to skip partial aggregation from the distinct keys in their first probe_rows rows, so a block whose cardinality changed partway through was judged by its head. They now sample rows across the whole block and estimate the block's distinct keys with the Haas-Stokes Duj1 estimator (as Postgres ANALYZE does for n_distinct). Remove enable_adaptive_partial_aggregation: partial_aggregation_mode now defaults to "estimate" (renamed from "probe"), and "always" turns adaptive skipping off. Rename the probe_rows setting to sample_rows. Signed-off-by: sampan <[email protected]>
…que; add raw_to_partial hook for custom aggregations Gives these aggregations Arrow specs with raw_to_partial so they run on the vectorized SHUFFLE_V2 engine and support adaptive partial aggregation. Std merges (count, mean, var) partials with Chan's formula; ValueCounter, TopKUnique and Quantile share a value->count state. Unsupported value types fall back to the Python engine. Adds AggregateFnV2.raw_to_partial so a custom aggregation can opt into adaptive partial aggregation on the Python engine. Adds --aggs to the groupby release benchmark and per-aggregation release tests. Signed-off-by: sampan <[email protected]>
Release benchmark (SF1000, low cardinality on l_extendedprice) showed the value->count Quantile state 3.5x slower than the Python engine: on mostly distinct values, hashing every (group, value) pair costs more than it saves. Quantile now keeps each group's values as a list (DataFusion's percentile_cont) and sorts once in finalize. Stable sorts on group ids now use the narrowest unsigned type, so numpy uses radix sort (~10x faster for <=65535 groups); this also speeds up AsList, ValueCounter and TopKUnique. Finalize replaces np.lexsort with an argsort by value followed by a stable argsort by group. Signed-off-by: sampan <[email protected]>
Adds cluster_memory_used_peak_gb (sum over nodes) and node_memory_used_peak_gb (busiest node) per case, from Prometheus. Signed-off-by: sampan <[email protected]>
… Std delta ids run from 0 to num_groups - 1, so 256 / 65536 groups still fit uint8 / uint16 (radix sort). Std's merge computes delta only for used rows instead of relying on np.where to drop NaN later. Signed-off-by: sampan <[email protected]>
…68118 Drop enable_adaptive_partial_aggregation, use the "estimate" mode and adaptive_partial_aggregation_sample_rows. Signed-off-by: sampan <[email protected]>
e0353d7 to
81df3c9
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 81df3c9. Configure here.
…all name clash Duj1 ran low when a few heavy keys (e.g. null) sat next to many unique ones, so those blocks pre-aggregated. Keys seen 3+ times in the sample now count as one distinct key each, and Duj1 runs on the remaining rows only. Rename the sampled key columns before grouping, so a key named count_all no longer collides with the count column. Signed-off-by: sampan <[email protected]>
…e-more-aggs Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]> # Conflicts: # python/ray/data/tests/test_hash_shuffle_v2.py
…blocks An all-null block has Arrow type null. Skip abs for it (older pyarrow has no abs kernel for null) and test every new aggregation on null-typed blocks, alone and next to numeric shards, under each partial-agg mode. Signed-off-by: sampan <[email protected]>
owenowenisme
left a comment
There was a problem hiding this comment.
approve with nit:
Non-blocking but add some validation for the data context vars(sample row & uniq ratio) that you added
Raise a ValueError naming the setting when partial_aggregation_mode is unknown, adaptive_partial_aggregation_sample_rows isn't a positive integer, or adaptive_partial_aggregation_unique_ratio_threshold isn't in [0, 1]. Signed-off-by: sampan <[email protected]>
…e-more-aggs Signed-off-by: sampan <[email protected]>
pyarrow's stubs lack pc.list_flatten and pc.list_parent_indices; suppress them as elsewhere in Ray Data. Import pyarrow.types explicitly. Signed-off-by: sampan <[email protected]>
`pd.Series.value_counts()` drops nulls by default while Arrow's `value_counts` counts them as values of their own, so the same logical data produced a different ValueCounter result depending on whether the block was Arrow- or pandas-backed. Block type is not something a user controls per block, so the aggregation must not depend on it. Pass `dropna=False` and normalize pandas' missing sentinels to a single canonical `None`, matching the Arrow semantics that #68202 specifies for this aggregation. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
Signed-off-by: sampan <[email protected]> # Conflicts: # python/ray/data/_internal/arrow_aggregation.py # python/ray/data/_internal/execution/operators/hash_aggregate_v2.py # python/ray/data/tests/test_hash_shuffle_v2.py
rayo5o
left a comment
There was a problem hiding this comment.
I ran the six aggregations end to end against master (where they still run on the Python engine) over 43 inputs: int8/uint8/uint32/uint64/int64/float32/float64 with nulls and ignore_nulls both ways, NaN, -0.0, bool, string/large_string/dictionary, decimal, timestamp, list and tensor values, an all-null group, null-typed blocks, int32/int64 blocks mixed, null keys, two keys, one key per row, and the custom Mean from the docs with raw_to_partial. Each ran under always, never and estimate, with one map task per block as in your e2e test. Apart from Std's NaN (in the description) and the changes below, the values match master, and the two inline comments are the only regressions I found.
A few output changes that aren't in the "Behavior changes" list yet:
AbsMaxkeeps the input type: int8, uint32 and float32 columns now give int8, uint32 and float32. Master returned int64 or double, which didn't match whatAbsMax.output_fielddeclares, so this is a fix. Still, downstream schemas change.TopKUniqueandValueCountervalues keep the input type too (int8 instead of int64, float32 instead of double,large_stringinstead ofstring,timestamp[ns]instead oftimestamp[us]).ValueCountercounts NaN once per group. Master gave one NaN entry per block, e.g. three entries of 3 instead of one of 9.Stdon a decimal column works now. On master it raisesTypeErrorincombine(float + Decimal).- The order of
ValueCounter's values differs from master. It was never specified, so this is just in case someone relies on it.
Std accuracy with |mean| ≫ std matches master. Against an exact Fraction computation, both are off by about 1e-8 at 1e9 + N(0, 1) and about 1e-3 at 1e12 + N(0, 0.01), where float64 runs out. The description's comparison is with sum / sum-of-squares, but master's Python Std already used the same parallel merge.
Your regression command at af7a235 with the CI lock (pyarrow 25.0.1, pandas 2.3.3): 1088 passed, 1 skipped, 1 failed. The failure is test_count, the same metrics-endpoint connection error you saw. The two map_groups timeouts didn't show up here.
| values = pc.cast(values, pa.float64()).to_numpy(zero_copy_only=False) | ||
| # Sort by value, then (stably) by group: sorted values per group. | ||
| # Much faster than np.lexsort. | ||
| by_value = np.argsort(values) |
There was a problem hiding this comment.
With few large groups this full sort dominates the reduce. All 40 map shards of 20M float64 values in 10 groups, fed to one reduce fn without Ray: the reduce takes 0.36 s on master (one pc.quantile per group) and 3.8 s here, and cProfile puts 4.3 s of 5.1 s in argsort. End to end with Ray (same data, 4 CPUs, median of 5) it's 4.6 s on master vs 7.8 s on this PR. Your SF1000 run at 84 groups is still faster overall, so the map-side savings cover it there.
Ordering by group only (_group_order, which is already a radix sort) and then np.partition for the two ranks per group gives identical results:
| groups (20M values) | argsort + group order |
group order + np.partition |
|---|---|---|
| 10 | 3.24 s | 0.50 s |
| 1,000 | 4.20 s | 1.22 s |
| 100,000 | 8.03 s | 5.03 s |
The partition version loops over groups in Python, so it may need a cutoff for millions of tiny groups.
| if block.num_rows == 0: | ||
| return block | ||
|
|
||
| if not _supports_types(block, aggs, specs) or _has_null_typed_target( |
There was a problem hiding this comment.
This also changes the low-cardinality path for value types the specs don't support. On master those queries pre-aggregate on the Python engine; here every map task ships all of its rows, even with partial_aggregation_mode="always". Decimal is the common case (AbsMax, Quantile and Std all reject it).
20M rows of decimal128, 10 keys, 40 blocks, 4 CPUs, default settings, median of 3:
| master | PR | |
|---|---|---|
map output per block (500k rows), AbsMax |
10 rows, 240 B | 500k rows, 12 MB |
groupby("k").aggregate(AbsMax("v")) |
3.84 s | 6.81 s |
groupby("k").aggregate(Quantile("v")) |
3.68 s | 7.23 s |
The same query on a float64 column takes 2.49 s vs 2.31 s, so it's the fallback path. At SF1000 scale this would ship the whole column through the shuffle and leave the aggregation to the few reducers that own the keys. Could the map pre-aggregate on the Python engine when its block's type is unsupported, and ship raw only for the all-null case?
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]>
…nto releases/2.61.0 (#68472) ## Description Cherry-pick of #68433 (`1729626bbb`) onto `releases/2.61.0`. Lets the upstream read or map fuse into the disk-shuffle writer, and sets the polars thread limit inside the task rather than through the runtime env. The pick applied without conflicts. Seven master commits that touch the same files are not on the release branch (#67143, #68158, #68202 and its revert #68383, #68319, #67570, #68118), so the picked files differ from master in five places. Reviewers from Data, please confirm none of those is a prerequisite. ## Testing Ran locally against the `releases/2.61.0` wheel (`7c8ca5ea51`) with the picked files overlaid: `test_hash_shuffle_v2.py`, `test_operator_fusion.py` and `test_execution_optimizer_advanced.py`, 232 passed, 2 skipped. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: You-Cheng Lin <[email protected]> Signed-off-by: elliot-barn <[email protected]> Co-authored-by: You-Cheng Lin <[email protected]>
`pd.Series.value_counts()` drops nulls by default while Arrow's `value_counts` counts them as values of their own, so the same logical data produced a different ValueCounter result depending on whether the block was Arrow- or pandas-backed. Block type is not something a user controls per block, so the aggregation must not depend on it. Pass `dropna=False` and normalize pandas' missing sentinels to a single canonical `None`, matching the Arrow semantics that #68202 specifies for this aggregation. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[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]>

Summary
This PR gives
AbsMax,Std,AsList,Quantile,ValueCounterandTopKUniqueArrow specs withraw_to_partial, so they run on the vectorized SHUFFLE_V2 aggregation engine and support adaptive partial aggregation (#68118). It also adds a publicAggregateFnV2.raw_to_partialhook, so custom aggregations on the Python engine can opt into adaptive partial aggregation too.Before
ArrowAggSpec. Any query that used one of them ran entirely on the Python engine (sort + per-group accumulate), even if it also usedMeanorSum.AggregateFnV2s had no way to support adaptive partial aggregation.After
max(abs(x))(withabs_checked), and the reducer takes themaxof those.(count, mean, var0), computed by Arrow'scount/mean/variance(ddof=0). The reducer merges partials with Chan's parallel formulaM2 = Σ nᵢ(varᵢ + (μᵢ − μ)²), as Spark, DataFusion and Trino do. This stays numerically stable when |mean| ≫ std.mode, stored as parallelvalues/countslist columns. Merging adds the counts per value. TopKUnique ranks the values within each group.array_agg/percentile_cont); merging concatenates the lists. Quantile sorts once in finalize and interpolates linearly. I tried Spark's value→count state for Quantile first, but on mostly distinct values (prices) it was 3.5× slower than master at low cardinality.ArrowAggSpechooks.grouped_raw/grouped_merge: per-group numpy math through a per-row group id. The id comes from adding a("__ray_row", "list")aggregation to the samegroup_by, which keeps null keys consistent.supports_type: unsupported value types (nested, extension, or non-numeric for the numeric aggregations) fall back to the Python engine, so results don't change for those types.AggregateFnV2.raw_to_partial(block)(public, optional). It returns one accumulator per row. When every aggregation in a Python-engine query implements it, map tasks may ship raw rows, tagged with a zero-byte__ray_raw_rowscolumn, and the reducer converts them to partials before combining. If any aggregation doesn't implement it, the map always pre-aggregates, as before.encode_lists=Trueand keyless (global) aggregations stay on the Python engine.Behavior changes
AbsMaxon an integer column holdingINT_MINnow raises (abs_checked). Before, Python'sabssilently produced a value that no longer fit the column type.Stdnow propagates NaN, consistent with vectorizedMean. The Python engine's NaN handling depended on how rows were laid out across blocks.flowchart TD subgraph Before subgraph BS[Subsystem: shuffle / aggregation] subgraph BC[Component: hash_aggregate_v2] B0{Every agg has ArrowAggSpec?} -->|"no (Std, AbsMax, Quantile, AsList, ValueCounter, TopKUnique, custom)"| B1[Python engine: sort + accumulate, always pre-aggregate] B0 -->|yes| B2[Vectorized engine, adaptive skip] end end end subgraph After subgraph AS[Subsystem: shuffle / aggregation] subgraph AC[Component: hash_aggregate_v2] A0{Every agg has ArrowAggSpec and supported value type?} -->|yes, now incl. the 6 aggs| A2[Vectorized engine, adaptive skip, grouped_raw / grouped_merge hooks] A0 -->|no| A1{Every agg overrides raw_to_partial?} A1 -->|yes| A3[Python engine, adaptive skip: raw rows + __ray_raw_rows marker] A1 -->|no| A4[Python engine, always pre-aggregate] end end end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class A1,A3 added class A0,A2 changedSubsystems
Shuffle / aggregation (
aggregate.py,_internal/arrow_aggregation.py,hash_aggregate_v2.py). Also docs (aggregating-data.md) and the groupby release benchmark.Why this is not a duplicate
There are no open PRs for vectorizing these aggregations or for a
raw_to_partialhook (searched open PRs). This extends #68118, which added adaptive partial aggregation only for aggregations that already had Arrow specs.Testing
AI assistance (Claude Code) was used to write this change. I reviewed the diff and ran the tests below locally.
New tests in
test_hash_shuffle_v2.py:ignore_nulls, low/high cardinality and partial-agg modes (always/never/mixed shards);raw_to_partialhook, plus always pre-aggregating without it;use_disk× mode compared against pandas.Updated
test_shuffle_elimination.py: the new aggregations now support complete aggregation.Regression run:
pytest python/ray/data/tests/{test_groupby_e2e,test_aggregations,test_agg_e2e,test_dataset_aggregrations,test_hash_shuffle_v2,test_shuffle_elimination,test_dataset_stats}.pygave 1034 passed, 3 failed.test_groupby_map_groups_multiple_batch_formatstimeouts were from a loaded box. They pass when rerun, and timing over 3 runs matches the base master commit (103–117s vs 111–122s).test_countfails because the dashboard/Prometheus metrics endpoint isn't available in my local env. It doesn't aggregate.Docs example (
raw_to_partialon the custom Mean) checked with modenever.Release tests (SF1000 TPC-H
lineitem, 500 partitions, SHUFFLE_V2), value columnl_extendedprice.aggregate_each_agg_{low,high}_cardinality, each aggregation timed on its own. Master = base commitc55def829eplus the same benchmark commit.raw_to_partial)aggregate_blockonce per group, and nearly every row is its own group. With Ray Data's default 30-minute no-progress watchdog, AbsMax and Std fail on master; the times above are with it off.customis unchanged, as expected: the map pre-aggregates either way.Local benchmark (4M rows, 100 keys, 4 CPUs, Python engine → vectorized): quantile 7.25s → 4.60s, value_counter 4.88s → 1.60s, topk_unique 3.53s → 1.77s. At 1M rows/~1M keys every aggregation is 24–62× faster.
🤖 Generated with Claude Code