Repository navigation
[Data][PreProc][1/4] Add exact TopKUnique aggregation - #66087
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces TopKUnique, an exact top-k-by-frequency unique aggregation function in Ray Data, along with comprehensive unit tests and documentation updates. The feedback highlights a performance optimization in the finalize method to avoid a redundant sorting attempt and a TypeError when None is present in the accumulator alongside other comparable types.
| def finalize(self, accumulator: Dict[str, List]) -> List[Any]: | ||
| pairs = list(zip(accumulator["values"], accumulator["counts"])) | ||
| try: | ||
| pairs.sort(key=lambda pair: (-pair[1], pair[0])) | ||
| except TypeError: | ||
| # Values aren't mutually comparable (e.g. mixed types, or None | ||
| # among them) - fall back to their string representation for a | ||
| # deterministic tie-break. | ||
| pairs.sort(key=lambda pair: (-pair[1], str(pair[0]))) | ||
| return [value for value, _ in pairs[: self._k]] |
There was a problem hiding this comment.
When ignore_nulls=False (the default) and the dataset contains null values, None is added to the accumulator. Since None is not comparable with other types (like str or int), the first sorting attempt pairs.sort(key=lambda pair: (-pair[1], pair[0])) will always raise a TypeError. This forces Python to abort the sort halfway through and re-sort the entire list using the fallback str(pair[0]) key. For high-cardinality columns, this redundant sorting attempt can significantly degrade performance.
To optimize this, we can use a single-pass sorting key that segregates None from other comparable types, avoiding the TypeError entirely in the common case where None is present alongside homogenous comparable types.
| def finalize(self, accumulator: Dict[str, List]) -> List[Any]: | |
| pairs = list(zip(accumulator["values"], accumulator["counts"])) | |
| try: | |
| pairs.sort(key=lambda pair: (-pair[1], pair[0])) | |
| except TypeError: | |
| # Values aren't mutually comparable (e.g. mixed types, or None | |
| # among them) - fall back to their string representation for a | |
| # deterministic tie-break. | |
| pairs.sort(key=lambda pair: (-pair[1], str(pair[0]))) | |
| return [value for value, _ in pairs[: self._k]] | |
| def finalize(self, accumulator: Dict[str, List]) -> List[Any]: | |
| pairs = list(zip(accumulator["values"], accumulator["counts"])) | |
| try: | |
| pairs.sort(key=lambda pair: (-pair[1], (0, "") if pair[0] is None else (1, pair[0]))) | |
| except TypeError: | |
| # Values aren't mutually comparable (e.g. mixed types) - fall back to | |
| # their string representation for a deterministic tie-break. | |
| pairs.sort(key=lambda pair: (-pair[1], str(pair[0]))) | |
| return [value for value, _ in pairs[: self._k]] |
There was a problem hiding this comment.
Good catch. The fallback re-sorted everything by str(). finalize now ranks in Arrow
(count desc, value asc, nulls last) and the Python fallback uses a null-aware key.
Tie-break documented.
owenowenisme
left a comment
There was a problem hiding this comment.
Could you merge master and reimplement the vectorized version?
Context: #66194
Adds TopKUnique, an exact top-k-by-global-frequency aggregation that returns a plain list of values (like Unique). Frequencies are counted per block, merged globally, and only then ranked, so a value that is moderately frequent in every block but frequent overall is correctly preferred over a per-block winner. Ties are broken deterministically by value (string-representation fallback for non-comparable types). Unlike the existing ApproximateTopK, the result is exact and requires no third-party dependency, at the cost of keeping all distinct values in the accumulator. This is groundwork for fitting encoder preprocessors (OneHotEncoder/MultiHotEncoder max_categories) via distributed aggregation instead of a driver-side counter merge. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
Address review feedback on the TopKUnique aggregation: - Rebuild TopKUnique on VectorizedAggregateFnV2 (added upstream in ray-project#66194). The reduce side now merges a whole column of partial accumulators per group with one Arrow group_by/sum instead of folding them pairwise in Python. _combine_column returns a valid accumulator (counts are kept and the top-k cut is only applied in finalize) because the hash-aggregate operator re-combines partially combined blocks with finalize=False before the final combine. The pairwise combine() is kept as the fallback for values Arrow can't group (whole lists, mixed types). - Rank in finalize with Arrow (count descending, value ascending, nulls last) when the values are sortable. The Python fallback uses a null-aware key, so a null tying on count no longer forces a str()-based re-sort of every value (which also ordered ints as "10" < "2"). - Treat any non-list-like row in a whole-list column as missing, so NaN/pd.NA rows no longer raise TypeError from tuple(). Tests: add unit tests for the column-wise merge (equivalence with the pairwise merge, re-combinability, whole-list fallback, missing list rows, ranking) and make the TopKUnique tests force one partial aggregate per block. Ray batches small shuffle inputs into a single map task, which reduced every group to one partial aggregate and meant the cross-partial merge was not exercised by the end-to-end tests at all. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
a88ffe6 to
38b55bf
Compare
Thanks @owenowenisme — rebased onto master and rebuilt One design note: I also found small test inputs never produced more than one partial |
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 38b55bf. Configure here.
| ranked = pc.sort_indices( | ||
| table, sort_keys=[("count", "descending"), ("value", "ascending")] | ||
| ) | ||
| return pc.take(table["value"], ranked[: self._k]).to_pylist() |
There was a problem hiding this comment.
Same-length lists become dicts
Medium Severity
Equal-length whole-list values are stored as tuples, which Arrow infers as structs. After group_by or finalize, to_pylist() materializes those structs as dicts like {'f0': 'a', 'f1': 'b'} instead of ['a', 'b']. _normalize_value only converts lists back to tuples, so dicts can also make combine raise TypeError on re-merge.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 38b55bf. Configure here.
- Name TopKUnique.combine's second parameter `new`, matching AggregateFnV2.combine, so the parameter docs are inherited from the base class (the API param coverage gate flagged `new_accumulator` as undocumented). - Build the accumulator list with a null row directly in the combine-column test instead of inserting None into an inferred list[dict], which pyrefly rejects. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
) Co-authored-by: Claude Fable 5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
…ggregation (#66088) ## Why are these changes needed? Encoder preprocessors (`OrdinalEncoder`, `OneHotEncoder`, `MultiHotEncoder`, `LabelEncoder`, `Categorizer`) currently fit through `compute_unique_value_indices`: a `map_batches` that emits per-block value counters, followed by a loop **on the driver** that merges them into global counts. `SimpleImputer(strategy="most_frequent")` has the same shape via `_get_most_frequent_values`. That driver-side merge is a scalability bottleneck, and because it is registered as a *callable stat*, it can never be batched with other statistics into a single `Dataset.aggregate()` query. This PR moves those fits onto the stat computation plan as real distributed aggregations: - The five encoders register `Unique` (or `TopKUnique` when `max_categories` is set) with the same `unique_values({col})` alias the transform code reads. - `SimpleImputer("most_frequent")` registers `TopKUnique(k=1, ignore_nulls=True)`. It returns the most frequent non-null value, breaks frequency ties by picking the smallest value, and yields no value for an all-null column, which gives the same results as before. It uses the vectorized column-wise merge, so no driver-side argmax helper is needed. - `Unique` (and `TopKUnique`) fall back to collecting values in Python when the vectorized path can't handle a column's type: types without an Arrow `unique`/`value_counts` kernel, such as tensor columns, and list-typed columns when the optional `polars` package isn't installed. Lists and arrays become tuples, so the encoders produce the same categories as before. `HASH` list encoding still requires `polars`, since a Python fallback can't reproduce polars' hashes. Behavior is preserved: `stats_` key names, the "contains null values … consider imputing" errors, list-column encoding (flatten vs whole-list), and global cross-partition top-k semantics for `max_categories` are all unchanged, which the existing suites verify. Each fit is now a single `Dataset.aggregate()` query per preprocessor with no driver-side merge. The legacy helpers `compute_unique_value_indices` and `_get_most_frequent_values` are removed; nothing uses them. Behavior notes for reviewers: - `ds.aggregate(Unique(...))` on a tensor column, or on a list column without `polars` installed, now works instead of raising. This comes from the fallback above and benefits any `Unique` user, not only the encoders. - Whole-list categories stay whole lists when merged from several partial aggregates, with or without `polars` (see the new tests below). - With `max_categories`, a null tied with a real value at the cut-off no longer raises "contains null values": nulls now rank last, whereas the old path broke ties by insertion order. Otherwise it raises in the same cases as before. - Pre-existing and unchanged: a block that holds *only* null rows of a list column is typed `null` rather than `list`, so its nulls count as a value and the fit raises. This depends on how rows are split into blocks, as it did before this PR; I'll file a follow-up. ## Related issue number N/A. Not a duplicate: searched open PRs/issues for encoder/imputer fit work; no overlap found (#66012 covers GPU transforms, not fitting). Part 2 of 4 of the preprocessor fitting series (RFC: #66090). Part 1 (`TopKUnique`, #66087) has merged; parts 3 and 4 (#66091, #66092) build on this. ## Checks - [x] I've signed off every commit (DCO). - [x] I've run pre-commit hooks — all hooks pass. - [x] Testing (macOS / Python 3.12, source build): - `pytest python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py` (torch not installed) — 411 passed, 5 skipped, 0 failed (clean master at the same base: 392 passed). Includes `test_preprocessors_arrow_backed.py`. Env matches CI pins (pandas 2.3.3, pyarrow 23.0.1, cloudpickle 3.1.1). - `pytest python/ray/data/tests/test_aggregations.py` — 62 passed (clean master: 57). - New tests: encoders/imputer assert they register plan aggregators (no callable stats); most_frequent never imputes null (including `None`, `NaN`, `pd.NA` and float32 `NaN`, even when they outnumber every real value); deterministic tie-break; most_frequent picks the value from counts summed across blocks; whole-list categories (`OrdinalEncoder(encode_lists=False)`, `OneHotEncoder`) stay whole lists when merged from several partial aggregates; encoders fit tensor columns (whole arrays, flattened arrays, `max_categories`); whole-list encoding with and without `polars`; `Unique` on tensor columns and on list columns without `polars`; `HASH` mode still requires `polars`; a null row in a list column adds no categories. AI assistance was used to draft this change (Claude Code); every line has been reviewed by the submitter. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
…t; migrate remaining scalers (#66092) ## Summary Turns on deferred, batched `Chain` fitting by default (added behind a flag in #66091), and moves the three remaining scalers onto aggregation-based fitting so they batch inside chains too. ## Before - `DataContext.enable_aggregation_based_preprocessors` defaulted to `False`, so `Chain.fit()` fitted members one by one: one full dataset scan per fittable member. - Even with the flag on, `MinMaxScaler`, `MaxAbsScaler` and `RobustScaler` ran their own `Dataset.aggregate()` inside `_fit`, so any chain containing them fell back to the sequential path. ## After - The flag defaults to `True`: `Chain.fit()` registers members' aggregations and computes them at the first `transform()` (or `transform_batch()` / serialization), one scan per dependency level. Opt out with `RAY_DATA_ENABLE_AGGREGATION_BASED_PREPROCESSORS=0` or the `DataContext` setting. The flip is isolated in this PR so it's trivially revertible. - `MinMaxScaler` (`Min`/`Max`), `MaxAbsScaler` (`AbsMax`) and `RobustScaler` register aggregators on the stat computation plan and support deferred fit. - `RobustScaler` now builds one single-quantile `ApproximateQuantile` sketch per statistic (`low_quantile`, `median`, `high_quantile`) instead of one sketch queried at three points. That's a little more sketch work, in exchange for keeping every `stats_` key unchanged. - All `stats_` keys and values are unchanged. KBins discretizers keep their eager fit (they post-process in `_fit_execute`); chains containing them, or any member without `_supports_deferred_fit`, still fit sequentially. ```mermaid flowchart TD subgraph Before subgraph BS[Subsystem: preprocessors] subgraph BC["Component: Chain.fit() (flag default off)"] B1[MinMaxScaler._fit: own aggregate scan] --> B2[MaxAbsScaler._fit: own aggregate scan] B2 --> B3[RobustScaler._fit: own aggregate scan] B3 --> B4[StandardScaler._fit: own aggregate scan] end end end subgraph After subgraph AS[Subsystem: preprocessors] subgraph AC["Component: Chain.fit() (flag default on)"] A1[MinMax / MaxAbs / Robust / Standard: register aggregators on plan] A1 --> A2["first transform(): one Dataset.aggregate() per dependency level"] end end end classDef removed fill:#ffcdd2,stroke:#c62828,color:#000 classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class B1,B2,B3,B4 removed class A1 changed class A2 added ``` ## Subsystems Preprocessors (`preprocessors/scaler.py`, default in `context.py`); computes statistics through Shuffle / aggregation (`Dataset.aggregate`) with no changes there. ## Related issue RFC: #66090. Final PR of the stack #66087 → #66088 → #66091 (all merged). Not a duplicate: the only open PR touching this flag is this one. ## Testing macOS / Python 3.12, env pinned to CI versions (pandas 2.3.3, pyarrow 23.0.1, cloudpickle 3.1.1, pytest 7.4.4): - `pytest python/ray/data/tests/preprocessors/test_chain.py python/ray/data/tests/preprocessors/test_scaler.py`: 64 passed, including a new test that a chain of MinMax/MaxAbs/Robust/Standard scalers on disjoint columns fits in a single aggregation query with the exact expected `stats_`. Existing `test_scaler.py` assertions pass unmodified. - `pytest python/ray/data/tests/preprocessors/ --ignore=python/ray/data/tests/preprocessors/test_torch.py` (torch not installed): 442 passed, 5 skipped, 0 failed (master: 441 passed). - `pytest python/ray/data/tests/test_aggregations.py`: 62 passed. - pre-commit, pyrefly (CI file set) and the API param coverage check pass. AI assistance was used to draft this change (Claude Code); every line has been reviewed by the submitter. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
…t; migrate remaining scalers (ray-project#66092) ## Summary Turns on deferred, batched `Chain` fitting by default (added behind a flag in ray-project#66091), and moves the three remaining scalers onto aggregation-based fitting so they batch inside chains too. ## Before - `DataContext.enable_aggregation_based_preprocessors` defaulted to `False`, so `Chain.fit()` fitted members one by one: one full dataset scan per fittable member. - Even with the flag on, `MinMaxScaler`, `MaxAbsScaler` and `RobustScaler` ran their own `Dataset.aggregate()` inside `_fit`, so any chain containing them fell back to the sequential path. ## After - The flag defaults to `True`: `Chain.fit()` registers members' aggregations and computes them at the first `transform()` (or `transform_batch()` / serialization), one scan per dependency level. Opt out with `RAY_DATA_ENABLE_AGGREGATION_BASED_PREPROCESSORS=0` or the `DataContext` setting. The flip is isolated in this PR so it's trivially revertible. - `MinMaxScaler` (`Min`/`Max`), `MaxAbsScaler` (`AbsMax`) and `RobustScaler` register aggregators on the stat computation plan and support deferred fit. - `RobustScaler` now builds one single-quantile `ApproximateQuantile` sketch per statistic (`low_quantile`, `median`, `high_quantile`) instead of one sketch queried at three points. That's a little more sketch work, in exchange for keeping every `stats_` key unchanged. - All `stats_` keys and values are unchanged. KBins discretizers keep their eager fit (they post-process in `_fit_execute`); chains containing them, or any member without `_supports_deferred_fit`, still fit sequentially. ```mermaid flowchart TD subgraph Before subgraph BS[Subsystem: preprocessors] subgraph BC["Component: Chain.fit() (flag default off)"] B1[MinMaxScaler._fit: own aggregate scan] --> B2[MaxAbsScaler._fit: own aggregate scan] B2 --> B3[RobustScaler._fit: own aggregate scan] B3 --> B4[StandardScaler._fit: own aggregate scan] end end end subgraph After subgraph AS[Subsystem: preprocessors] subgraph AC["Component: Chain.fit() (flag default on)"] A1[MinMax / MaxAbs / Robust / Standard: register aggregators on plan] A1 --> A2["first transform(): one Dataset.aggregate() per dependency level"] end end end classDef removed fill:#ffcdd2,stroke:#c62828,color:#000 classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class B1,B2,B3,B4 removed class A1 changed class A2 added ``` ## Subsystems Preprocessors (`preprocessors/scaler.py`, default in `context.py`); computes statistics through Shuffle / aggregation (`Dataset.aggregate`) with no changes there. ## Related issue RFC: ray-project#66090. Final PR of the stack ray-project#66087 → ray-project#66088 → ray-project#66091 (all merged). Not a duplicate: the only open PR touching this flag is this one. ## Testing macOS / Python 3.12, env pinned to CI versions (pandas 2.3.3, pyarrow 23.0.1, cloudpickle 3.1.1, pytest 7.4.4): - `pytest python/ray/data/tests/preprocessors/test_chain.py python/ray/data/tests/preprocessors/test_scaler.py`: 64 passed, including a new test that a chain of MinMax/MaxAbs/Robust/Standard scalers on disjoint columns fits in a single aggregation query with the exact expected `stats_`. Existing `test_scaler.py` assertions pass unmodified. - `pytest python/ray/data/tests/preprocessors/ --ignore=python/ray/data/tests/preprocessors/test_torch.py` (torch not installed): 442 passed, 5 skipped, 0 failed (master: 441 passed). - `pytest python/ray/data/tests/test_aggregations.py`: 62 passed. - pre-commit, pyrefly (CI file set) and the API param coverage check pass. AI assistance was used to draft this change (Claude Code); every line has been reviewed by the submitter. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Abhishek Verma <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>


Why are these changes needed?
Adds
TopKUnique, an exact top-k-by-global-frequency aggregation, alongside theexisting aggregations in
python/ray/data/aggregate.py.Frequencies are counted per block, merged globally, and only then ranked, so a
value that is moderately frequent in every block but frequent overall is
correctly preferred over a per-block winner (the same global semantics the
encoder preprocessors already guarantee via
test_one_hot_encoder_max_categories_global_sum_across_partitions). Ties arebroken deterministically by value, falling back to the string representation
for non-comparable types.
Relationship to
ApproximateTopK: that aggregation is approximate, works on adatasketchesfrequent-strings sketch (extra dependency), and returnsvalue/count records.
TopKUniqueis exact, has no third-party dependency, andreturns a plain list of values (like
Unique) — at the cost of keeping alldistinct values in the accumulator. The two docstrings cross-reference each
other.
Motivation: this is groundwork for fitting encoder preprocessors
(
OneHotEncoder/MultiHotEncoderwithmax_categories) via distributedaggregation instead of a driver-side counter merge (follow-up PR), but it is
independently useful as a public aggregation.
Related issue number
N/A. Duplicate-work check: searched open PRs/issues for top-k aggregation work;
the only adjacent open PR is #66012 (GPU preprocessor transforms), which does
not overlap.
Checks
pre-commit run --files ...) — all hooks pass.pytest python/ray/data/tests/test_aggregations.py— 57 passed (21TestTopKUniquecases incl. column-wise merge vs pairwise equivalence, re-combinability, whole-list
fallback, missing list rows, null tie ordering, many groups x many blocks).
Env matches CI pins (pandas 2.3.3, pyarrow 23.0.1).
TopKUniquetodoc/source/data/api/aggregate.rst.AI assistance was used to draft this change (Claude Code); every line has been
reviewed by the submitter.
🤖 Generated with Claude Code