Repository navigation
[Data][PreProc][2/4] Fit encoders and SimpleImputer via distributed aggregation - #66088
Conversation
|
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. |
48c083e to
a39ef2a
Compare
eab3104 to
3a6d955
Compare
There was a problem hiding this comment.
Code Review
This pull request migrates various Ray Data preprocessors (encoders and SimpleImputer) from using legacy driver-side callable stats to using distributed aggregations (Unique, TopKUnique, and ValueCounter). This change improves performance and scalability by leveraging Ray's distributed query engine. I have reviewed the changes and identified a potential issue in the null-filtering logic within the new _most_frequent_from_value_counts helper function, where using pd.isna(value) is recommended over the current manual check to better handle various null sentinels and float types.
) ## What broke Calling a preprocessor's `transform_batch` inside a `map_batches(batch_format="pandas")` UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading from 2.55: ```python ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}]) scaler = StandardScaler(columns=["n"]).fit(ds) ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all() ``` | input | error | |---|---| | int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641 was truncated converting to int64` | | string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError: ArrowStringArray requires a PyArrow (chunked) array of large_string type` | | a list column merely *present* in the batch | `TypeError: data type 'list<item: string>[pyarrow]' not understood` | The third needs no list-typed input to the preprocessor — a `tags` column sitting unused in the batch is enough while a float column is scaled. ## Why `_transform_batch` converted the whole batch with `pa.Table.from_pandas`, which records the input dtypes in the table's pandas schema metadata, ran `_transform_arrow`, and converted back with `to_pandas`. The transform changes column types — int64 to double for a scaler, string to int64 for an ordinal encoding — but the metadata still described the input, so the conversion back cast the results to their pre-transform dtypes. That round trip landed in 2.54 (#59810). 2.56 (#63017) made pandas batches Arrow-backed, which is what made those cast-backs fail. So this is a latent bug that 2.56 exposed rather than one 2.56 introduced: the same call already failed on 2.55 when handed an Arrow-backed frame directly. ## The fix Stop round-tripping the batch. Only the columns the preprocessor reads (`get_input_columns`) cross into Arrow, without the metadata, and only the ones it writes (`get_output_columns`) come back. The result is a shallow copy of the caller's frame with those columns replaced, so untouched columns, the index, the axis names and `attrs` never leave pandas — there is nothing to rebuild. - A written column that keeps its Arrow type keeps the dtype of the column it replaces (a scaled `Float64` stays `Float64`). - Otherwise it keeps that column's backing. An Arrow-backed column stays Arrow-backed whatever `enable_arrow_backed_pandas_conversion` says — the flag governs how Ray converts its own blocks, not the caller's columns — except for the types Ray never maps to an Arrow-backed dtype (extension, dictionary, null), which go through its block conversion as before. A NumPy-backed column converts plainly, and a newly created column follows the frame. - That Arrow-to-pandas type mapping moves unchanged from a closure in `ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so both paths share one rule. - A preprocessor that declares no columns falls back to sending the whole frame. Writing columns back by position needs `_transform_arrow` to return the rows it was given, in order. A changed row count now raises a `ValueError`, and the `_transform_arrow` docstring states the contract. All three built-in `_transform_arrow` implementations are column transforms and satisfy it. ## Behaviour changes Both come from untouched columns no longer being re-inferred from Arrow: - An object column of numbers stays `object`; it used to come back `int64` / `float64`. - Integer column labels stay integers; they used to be turned into strings. And one for implementers: `_transform_arrow` on a pandas batch now receives only the declared input columns, and must not change the rows. The previous code tolerated a filtering transform by carrying the index through as a column; it now raises instead. ## Not a fix for `enable_arrow_backed_pandas_conversion=False` mitigates this only for Arrow-block sources. A pandas block built from an already-Arrow-backed frame — what `pd.read_parquet(..., dtype_backend="pyarrow")` returns — never undergoes an Arrow-to-pandas conversion, so the flag does not reach it; this change fixes that path. Two related gaps are left for follow-ups rather than widening this PR: - `Preprocessor.transform(ds)` has the same stale-metadata defect for a dataset built from an Arrow-backed pandas frame with the flag set to `False` (it works with the default). - `transform_batch(pa.Table)` returns a table that still carries the caller's pandas metadata, so calling `.to_pandas()` on the result can fail the same way. ## Not a duplicate No open PR touches `_transform_batch` or this pandas/Arrow round trip. The open preprocessor work (#66088, #66091) is about how preprocessors are *fitted* and does not change the transform path; #60533 adds a `drop` option to the one-hot encoders in `encoder.py`. The other open Arrow/pandas PRs are elsewhere: #65539 is schema unification for empty datasets, #63938 preserves `CategoricalDtype` in `Schema.types`. No open issue covers it either. #64765, the umbrella 2.56 `to_pandas` regression, is closed, fixed by #64768 — which added the `enable_arrow_backed_pandas_conversion` opt-out and left this round trip untouched. ## Testing 35 `transform_batch` cases added to `python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`: - `test_transform_batch_inside_a_pandas_udf` — the three reported preprocessors through a pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`. - `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the flag does not cover. - `test_transform_batch_passes_through_an_untouched_list_column` — the list-column case. - `test_transform_batch_matches_the_input_backing` / `..._decides_the_backing_per_column` — NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame keeps both. - `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the same holds for all three preprocessors with `enable_arrow_backed_pandas_conversion=False`. - `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable `Int64`, `boolean` and `string` columns come back intact, including a value past 2**53. - `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` — object columns of numbers, a categorical over pandas strings, Python lists. - `test_transform_batch_preserves_the_index` — named, `MultiIndex` and tz-aware `DatetimeIndex` on both backings, plus the columns axis name. - `test_transform_batch_keeps_integer_column_labels`, `..._does_not_modify_the_callers_frame`, `..._rejects_a_transform_that_changes_the_row_count`, `..._on_an_empty_batch`. The cases assert on values rather than on "did not raise": where the stale metadata permitted the cast, the result was silently wrong rather than an error — an ordinal encoding coming back as the strings `"0"`, `"1"`, `"2"`. Against the unmodified source, 21 of the 35 fail: - 15 are the reported crash on Arrow-backed input. - 5 are the behaviour changes above: master re-typed untouched object and categorical columns and stringified integer labels. - 1 is the new contract: master tolerated a filtering `_transform_arrow`; this raises. The other 14 pass on master too and are controls — the NumPy-backed halves, the empty batch, and the pass-through dtype cases, which guard against a regression a naive fix would introduce. ``` $ PYTHONPATH=python/ray/data/tests python -m pytest -q \ python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py 381 passed, 5 skipped $ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py 30 passed ``` The three reported repros were also run end to end through `map_batches` in Ray workers. `test_torch.py` is excluded because `torch` is not installed in this environment; it is untouched by this change. Pre-commit passes on all three changed files. Only the declared columns are converted, so wide frames stop paying for every column: `StandardScaler(columns=["n"]).transform_batch` on a 1000-column × 2k-row NumPy frame goes from ~27 ms to under 1 ms. AI assistance was used for this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Aarrya <[email protected]>
Replaces the driver-side counter merge in preprocessor fitting with distributed aggregations: - OrdinalEncoder, OneHotEncoder, MultiHotEncoder, LabelEncoder and Categorizer now register Unique (or TopKUnique when max_categories is set) aggregators on the stat computation plan instead of the compute_unique_value_indices callable stat. That callable ran a map_batches over the dataset and then merged per-block counters in a loop on the driver - a scalability bottleneck. - SimpleImputer(strategy="most_frequent") likewise moves from _get_most_frequent_values to the existing ValueCounter aggregation plus an argmax post-processing step that skips nulls (an Arrow-backed column reports nulls as value_counts entries) and breaks frequency ties deterministically by picking the smallest value. Behavior is unchanged: stats_ keys, null-handling errors, list-column encoding, and global (cross-partition) top-k semantics for max_categories are all preserved, and each fit is now a single Dataset.aggregate() query per preprocessor. The legacy helpers compute_unique_value_indices and _get_most_frequent_values are kept for backwards compatibility. Note: fitting an encoder with encode_lists=False on a list-typed Arrow column now goes through Unique, which uses polars for list-column uniqueness (same as any Unique aggregation on list columns today). Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
…view feedback - Use TopKUnique(k=1, ignore_nulls=True) for SimpleImputer(strategy= "most_frequent") instead of ValueCounter plus a driver-side argmax helper. It yields the same result (most frequent non-null value, ties broken by the smallest value, no value for an all-null column) with the vectorized column-wise merge, and removes the null-filtering helper that review flagged for missing pd.NA and numpy float NaN sentinels. - Add tests that null sentinels (None, NaN, pd.NA, float32 NaN) are never the most frequent value even when they outnumber every real value, and that the value is chosen from counts summed across blocks. - Add a regression test that whole-list categories (OrdinalEncoder with encode_lists=False, OneHotEncoder) stay whole lists when merged from several partial aggregates. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
e466eb3 to
e3220b6
Compare
|
Edge Case: ds = ray.data.from_items([{"t": np.array([1, 2])}, {"t": np.array([3, 4])}, {"t": np.array([1, 2])}])
print(OneHotEncoder(["t"]).fit(ds).stats_) |
|
Whole-list encoding (e.g. import ray
from ray.data.preprocessors import OneHotEncoder
ds = ray.data.from_items([{"tags": ["a", "b"]}, {"tags": ["c"]}, {"tags": ["a", "b"]}])
print(OneHotEncoder(["tags"]).fit(ds).stats_) |
…-project#66578) ## What broke Calling a preprocessor's `transform_batch` inside a `map_batches(batch_format="pandas")` UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading from 2.55: ```python ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}]) scaler = StandardScaler(columns=["n"]).fit(ds) ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all() ``` | input | error | |---|---| | int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641 was truncated converting to int64` | | string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError: ArrowStringArray requires a PyArrow (chunked) array of large_string type` | | a list column merely *present* in the batch | `TypeError: data type 'list<item: string>[pyarrow]' not understood` | The third needs no list-typed input to the preprocessor — a `tags` column sitting unused in the batch is enough while a float column is scaled. ## Why `_transform_batch` converted the whole batch with `pa.Table.from_pandas`, which records the input dtypes in the table's pandas schema metadata, ran `_transform_arrow`, and converted back with `to_pandas`. The transform changes column types — int64 to double for a scaler, string to int64 for an ordinal encoding — but the metadata still described the input, so the conversion back cast the results to their pre-transform dtypes. That round trip landed in 2.54 (ray-project#59810). 2.56 (ray-project#63017) made pandas batches Arrow-backed, which is what made those cast-backs fail. So this is a latent bug that 2.56 exposed rather than one 2.56 introduced: the same call already failed on 2.55 when handed an Arrow-backed frame directly. ## The fix Stop round-tripping the batch. Only the columns the preprocessor reads (`get_input_columns`) cross into Arrow, without the metadata, and only the ones it writes (`get_output_columns`) come back. The result is a shallow copy of the caller's frame with those columns replaced, so untouched columns, the index, the axis names and `attrs` never leave pandas — there is nothing to rebuild. - A written column that keeps its Arrow type keeps the dtype of the column it replaces (a scaled `Float64` stays `Float64`). - Otherwise it keeps that column's backing. An Arrow-backed column stays Arrow-backed whatever `enable_arrow_backed_pandas_conversion` says — the flag governs how Ray converts its own blocks, not the caller's columns — except for the types Ray never maps to an Arrow-backed dtype (extension, dictionary, null), which go through its block conversion as before. A NumPy-backed column converts plainly, and a newly created column follows the frame. - That Arrow-to-pandas type mapping moves unchanged from a closure in `ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so both paths share one rule. - A preprocessor that declares no columns falls back to sending the whole frame. Writing columns back by position needs `_transform_arrow` to return the rows it was given, in order. A changed row count now raises a `ValueError`, and the `_transform_arrow` docstring states the contract. All three built-in `_transform_arrow` implementations are column transforms and satisfy it. ## Behaviour changes Both come from untouched columns no longer being re-inferred from Arrow: - An object column of numbers stays `object`; it used to come back `int64` / `float64`. - Integer column labels stay integers; they used to be turned into strings. And one for implementers: `_transform_arrow` on a pandas batch now receives only the declared input columns, and must not change the rows. The previous code tolerated a filtering transform by carrying the index through as a column; it now raises instead. ## Not a fix for `enable_arrow_backed_pandas_conversion=False` mitigates this only for Arrow-block sources. A pandas block built from an already-Arrow-backed frame — what `pd.read_parquet(..., dtype_backend="pyarrow")` returns — never undergoes an Arrow-to-pandas conversion, so the flag does not reach it; this change fixes that path. Two related gaps are left for follow-ups rather than widening this PR: - `Preprocessor.transform(ds)` has the same stale-metadata defect for a dataset built from an Arrow-backed pandas frame with the flag set to `False` (it works with the default). - `transform_batch(pa.Table)` returns a table that still carries the caller's pandas metadata, so calling `.to_pandas()` on the result can fail the same way. ## Not a duplicate No open PR touches `_transform_batch` or this pandas/Arrow round trip. The open preprocessor work (ray-project#66088, ray-project#66091) is about how preprocessors are *fitted* and does not change the transform path; ray-project#60533 adds a `drop` option to the one-hot encoders in `encoder.py`. The other open Arrow/pandas PRs are elsewhere: ray-project#65539 is schema unification for empty datasets, ray-project#63938 preserves `CategoricalDtype` in `Schema.types`. No open issue covers it either. ray-project#64765, the umbrella 2.56 `to_pandas` regression, is closed, fixed by ray-project#64768 — which added the `enable_arrow_backed_pandas_conversion` opt-out and left this round trip untouched. ## Testing 35 `transform_batch` cases added to `python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`: - `test_transform_batch_inside_a_pandas_udf` — the three reported preprocessors through a pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`. - `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the flag does not cover. - `test_transform_batch_passes_through_an_untouched_list_column` — the list-column case. - `test_transform_batch_matches_the_input_backing` / `..._decides_the_backing_per_column` — NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame keeps both. - `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the same holds for all three preprocessors with `enable_arrow_backed_pandas_conversion=False`. - `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable `Int64`, `boolean` and `string` columns come back intact, including a value past 2**53. - `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` — object columns of numbers, a categorical over pandas strings, Python lists. - `test_transform_batch_preserves_the_index` — named, `MultiIndex` and tz-aware `DatetimeIndex` on both backings, plus the columns axis name. - `test_transform_batch_keeps_integer_column_labels`, `..._does_not_modify_the_callers_frame`, `..._rejects_a_transform_that_changes_the_row_count`, `..._on_an_empty_batch`. The cases assert on values rather than on "did not raise": where the stale metadata permitted the cast, the result was silently wrong rather than an error — an ordinal encoding coming back as the strings `"0"`, `"1"`, `"2"`. Against the unmodified source, 21 of the 35 fail: - 15 are the reported crash on Arrow-backed input. - 5 are the behaviour changes above: master re-typed untouched object and categorical columns and stringified integer labels. - 1 is the new contract: master tolerated a filtering `_transform_arrow`; this raises. The other 14 pass on master too and are controls — the NumPy-backed halves, the empty batch, and the pass-through dtype cases, which guard against a regression a naive fix would introduce. ``` $ PYTHONPATH=python/ray/data/tests python -m pytest -q \ python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py 381 passed, 5 skipped $ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py 30 passed ``` The three reported repros were also run end to end through `map_batches` in Ray workers. `test_torch.py` is excluded because `torch` is not installed in this environment; it is untouched by this change. Pre-commit passes on all three changed files. Only the declared columns are converted, so wide frames stop paying for every column: `StandardScaler(columns=["n"]).transform_batch` on a 1000-column × 2k-row NumPy frame goes from ~27 ms to under 1 ms. AI assistance was used for this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Aarrya <[email protected]>
Fitting the encoders through aggregations regressed two cases that worked with the previous driver-side counting: - Arrow has no unique/value_counts kernel for extension types such as tensors, so a column of arrays raised ArrowNotImplementedError. - Arrow's uniqueness of a list-typed column needs the optional polars package, so whole-list encoding raised ImportError without it. The encoders now use a private Unique subclass that tries the vectorized path first and only falls back to collecting the values in Python when Arrow can't handle the column's type (ArrowNotImplementedError or a missing polars). Lists and arrays become tuples, matching the categories the previous implementation produced. TopKUnique likewise falls back to counting in Python for types without a value_counts kernel, which covers tensor columns with max_categories. Transform on tensor columns is unchanged: it already raised on master. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
Good catch. Fixed: tensor columns now fit as before, and TopKUnique has the same fallback. transform on tensor columns already raised on master, so that part is unchanged. |
Fixed: whole-list encoding no longer needs polars; it falls back to Python only when polars isn't available. Added a test with polars blocked. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
Reviewed by Cursor Bugbot for commit 10e2d44. Configure here.
…vior - Remove compute_unique_value_indices and _get_most_frequent_values. The encoders and SimpleImputer now fit through aggregations, so nothing calls them, and they were never exported. - Add a test that the default OrdinalEncoder (list encoding on) splits each array of a tensor column into its elements, as the previous fit path did. - Add a test that merging per-block partials keeps array and list categories whole, both on the vectorized path and on the Python fallback used when polars is not installed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
rayhhome
left a comment
There was a problem hiding this comment.
A few more review comments!
| TopKUnique( | ||
| on=col, | ||
| k=self._max_categories[col], | ||
| ignore_nulls=False, |
There was a problem hiding this comment.
With max_categories, null list elements can now raise "contains null values". Is this intended?
There was a problem hiding this comment.
Not a regression: across Arrow and pandas inputs, it raises only where master did. One difference: a null tied with a real value at the cutoff no longer raises (nulls rank last; master broke ties by insertion order). Separately, a block made only of null rows still raises at fit, as on master; that’s pre-existing and partition-dependent, and I’ll file a follow-up.
| # Arrow has no `value_counts` kernel for this type (e.g. extension | ||
| # types such as tensors), so count in Python over hashable values. | ||
| counter = collections.Counter( | ||
| tuple(value) |
There was a problem hiding this comment.
This logic seems to be the same as the body of _to_hashable. Can we move the helper here and use in both places?
There was a problem hiding this comment.
Done. _to_hashable now lives in aggregate.py and is shared by Unique and TopKUnique. The encoder-side copy is gone along with the _EncoderUnique subclass.
| return tuple(value) if isinstance(value, (list, tuple, np.ndarray)) else value | ||
|
|
||
|
|
||
| class _EncoderUnique(Unique): |
There was a problem hiding this comment.
Is this class introduced specifically to handle the polars not installed case? TopKUnique seems to also handle this but does not introduce a new class; I think it would be easier to follow if we stick with one shared approach for both.
There was a problem hiding this comment.
Agreed. Moved the fallback into Unique itself, matching TopKUnique, with one shared helper. The encoders use Unique directly again.
| ctx = ray.data.DataContext.get_current() | ||
| original = ctx.shuffle_input_batch_bytes | ||
| # One partial aggregate per block (Ray otherwise batches small inputs together). | ||
| ctx.shuffle_input_batch_bytes = 1 |
There was a problem hiding this comment.
We may use the data_context_override fixture here so that the state can be restored on failure.
There was a problem hiding this comment.
Switched to restore_data_context, which is function-scoped. data_context_override is module-scoped, so its override would carry over into later tests in the file.
| return int(category) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("polars_available", [True, False]) |
There was a problem hiding this comment.
I think this test can be merged into test_whole_list_encoders_fit_without_polars through parametrization.
There was a problem hiding this comment.
Merged into parametrized tests.
| assert imputer.stats_ == {"most_frequent(A)": "a"} | ||
|
|
||
|
|
||
| def test_most_frequent_never_imputes_null(): |
There was a problem hiding this comment.
This test can be merged into test_most_frequent_ignores_null_sentinels through parametrization.
There was a problem hiding this comment.
Merged into parametrized tests.
- Move the Python fallback for column types the vectorized path can't handle (types without an Arrow unique kernel, such as tensors, and list-typed columns when polars isn't installed) from a private encoder subclass into Unique itself, matching how TopKUnique handles them. The encoders use Unique directly again. HASH list encoding keeps requiring polars, since a Python fallback can't reproduce polars hashes. - Share one _to_hashable helper between Unique and TopKUnique. - Pin that a missing row in a list column contributes no categories. - Tests: restore DataContext changes with the restore_data_context fixture, and merge the polars and null-sentinel tests into parametrized ones. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Abhishek Verma <[email protected]>
…f by default) (#66091) ## Why are these changes needed? `Chain.fit()` runs one full dataset scan per fittable member — and because Ray Datasets are lazy, each scan also re-executes the upstream read/transform pipeline. A `Chain(SimpleImputer, StandardScaler, OrdinalEncoder)` reads the data three times to fit. Every fit statistic is the answer to an aggregation query (mean/std, unique values, value counts), and members that touch disjoint columns are independent. This PR adds an opt-in fast path that batches those queries: - With `DataContext.enable_aggregation_based_preprocessors` set (env: `RAY_DATA_ENABLE_AGGREGATION_BASED_PREPROCESSORS`, **default off**), `Chain.fit()` only registers each member's aggregations on its stat computation plan and returns. - The first `transform()` schedules the scans (new `preprocessors/dag.py`, two pure functions). `_fit_order` picks a fit-time order in which members touching disjoint columns can share a scan; `_fit_levels` then gives each member a level (a layered topological sort: a member depends on an earlier one iff it reads a column the earlier one writes). Each level's aggregations run as **one** `Dataset.aggregate()` call; results are routed into each member's `stats_` by aggregator alias; fitted members then transform the (lazy) fit dataset so the next level aggregates over transformed data. Cost: `max(levels) + 1` scans instead of one per member — a chain of independent members fits in a single scan. - Statistics are computed over **the dataset passed to `fit()`** (stashed on the chain), never over the dataset being transformed, so the fitted values are identical to sequential fitting even when a different dataset is transformed first. **The user-visible behavioral change** (why this is behind a default-off flag): with the flag on, `Chain.fit()` returns with member `stats_` empty; they materialize at the first `transform()`, `transform_batch()`, or serialization. An RFC issue for this semantic is open at #66090 (#66090). Safety properties (all in this PR, with tests — the flag isn't safe without them): 1. **Opt-in per class.** A new `_supports_deferred_fit` marker is set only on preprocessors whose `_fit` purely registers plan aggregators (StandardScaler, SimpleImputer, and the five encoders as of the previous PR). A chain containing any unmarked fittable member — third-party subclasses, discretizers, CountVectorizer — keeps today's sequential eager fit for the whole chain. 2. **Serial fallback** (with a warning) at materialization time if a member registered a custom callable stat. 3. **Idempotence**: repeated `transform()` never re-runs aggregations. 4. **Serialization-safe**: `serialize()` and plain pickling of a fitted-but-never-transformed chain materialize the stats first, in dependency order; the fit dataset itself is never pickled. 5. Non-fittable members (e.g. `Concatenator`) take part in scheduling with their read/write columns, so a member reading a non-fittable's output only aggregates after that transform is applied. 6. Nested chains defer recursively and fit on the data flowing into their chain position. 7. Two members needing the same aggregation alias in one level run in separate query batches instead of colliding on a result column. 8. **Undeclared members are barriers.** A member that doesn't declare both its input and output columns (the default for user-defined preprocessors) is treated as reading and writing every column: later members compute statistics only after its transform is applied. 9. **Transform order.** Transforms on the fit dataset are applied in fit order, stopping at the first member that hasn't fitted yet, and a member computes statistics only once every member it depends on (and every member before those) has been transformed. 10. **Partly pre-filled stats.** Every registered aggregation runs even if `stats_` is already partly filled (e.g. `Categorizer` with dtypes given for some columns). 11. **Fit dataset released.** The dataset passed to `fit()` is released once statistics are computed. 12. **Safe fit-time reordering.** Only members that touch disjoint columns are fitted out of chain order. Members that share any column (including two readers, since `Concatenator` drops its inputs) and members without declared columns keep their chain order. The stored chain and the `transform()` order are unchanged. Also extracts the aggregate-execution half of `StatComputationPlan.compute` into a shared `execute_aggregate_specs` helper (no behavior change) and gives `Chain` `get_input_columns`/`get_output_columns` (inputs exclude columns produced by an earlier member; both lists are de-duplicated in order). With the flag off (the default), behavior is unchanged; an explicit test asserts the eager path. The level-based scheduler (`_fit_levels` / `_fit_order`) was contributed by @goutamvenkat-anyscale during review. ## Related issue number RFC: # [66090](#66090). Not a duplicate: searched open PRs/issues for chain fit / preprocessor aggregation work; no overlap found. Depends on the [encoder-aggregation PR](#66088) (stacked; will rebase once it lands). ## 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/test_chain.py` — 35 passed (deferral semantics, eager-vs-deferred stats equality, one-query batching of independent members, one-scan-per-level, fit levels, fit order and the measured scan reduction, no re-aggregation on repeated transform, fit-dataset semantics, non-fittable ordering, unmarked-member fallback, callable-stat serial fallback, alias collision, nested chain, serialization, transform_batch, flag-off eager path, undeclared and partially declared member barriers (in levels and in fit order), members that skip `Preprocessor.__init__`, transform ordering, partly pre-filled stats, fit-dataset release, Chain input/output columns). - `pytest python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py` (torch not installed) — 441 passed, 5 skipped, 0 failed (clean master at the same base: 392 passed). - `pytest python/ray/data/tests/test_aggregations.py` — 62 passed. - Env matches CI pins (pandas 2.3.3, pyarrow 23.0.1, cloudpickle 3.1.1, pytest 7.4.4). - Each safety rule was checked by removing it and confirming a test fails. A brute-force check of the scheduler over 200k random chains found no case where a member fits before the data it needs is ready. 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]> Signed-off-by: Goutam <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Goutam <[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]>
…th existing category values (#67467) ## Why are these changes needed? In `ray.data.preprocessors.SimpleImputer._transform_pandas`, two bugs caused imputation on `pd.Categorical` columns to raise `TypeError` or `ValueError`: 1. **Append mode (`output_columns` specified, `output_column != column`) overwrote the newly added category**: Previously, `df[output_column] = df[column].cat.add_categories([value])` was executed *before* `df[output_column] = df[column].copy(deep=True)`. Because `df[column]` still held the original categories without `value`, copying `df[column]` into `df[output_column]` immediately discarded the added category, causing `df.fillna({output_column: value}, inplace=True)` to fail with: `TypeError: Cannot setitem on a Categorical with a new category (..., set the categories first)` 2. **Imputing an existing category value (`strategy="most_frequent"` or `strategy="constant"` where `fill_value` is already in `cat.categories`) crashed**: Calling `cat.add_categories([value])` unconditionally without checking `value not in df[output_column].cat.categories` raised: `ValueError: new categories must not include old categories: {...}` In addition, because `df[column].values` on a `pd.Categorical` column is a `pandas.Categorical` ExtensionArray rather than an `np.ndarray`, the writeable-copy guard also checks `is_categorical_dtype(df.dtypes[column]) and not df[column].values.codes.flags.writeable` so in-place `fillna` does not fail on zero-copy / read-only batches when `add_categories` is skipped. ### Changes - Copy `df[column]` into `df[output_column]` first when `output_column != column` or the backing array / categorical codes buffer is non-writeable (`not df[column].values.codes.flags.writeable`). - Guard `df[output_column].cat.add_categories([value])` with `value not in df[output_column].cat.categories`. - Add unit tests in `python/ray/data/tests/preprocessors/test_imputer.py` covering categorical columns in append mode, `strategy="constant"` with an existing category on read-only categorical codes, and `strategy="most_frequent"` on categorical columns. ### Duplicate-work & testing notes - Searched open and closed issues/PRs in `ray-project/ray` for `SimpleImputer` and `add_categories`; no existing issue or PR covers these two categorical bugs. - Tested locally with `pytest python/ray/data/tests/preprocessors/test_imputer.py -k "test_imputer_categorical_append_and_existing_category or test_imputer_all_nan_raise_error or test_imputer_constant_categorical"` (`3 passed`). - AI assistance was used while preparing and verifying this PR. ### Acknowledgments Credit to @abhishekverma-ray (#66091, #66088), @AarryaSaraf (#65272), @rayhhome (#61028), and @cem-anyscale (#58321) for their foundational work on `SimpleImputer` and `output_columns` support in `ray.data.preprocessors`, and to @gemini-code-assist[bot] and @cursor[bot] for catching the `Categorical.codes.flags.writeable` check. ## Checks - [x] I've signed off every commit(by making the commit message contain `Signed-off-by: ...`) - [x] I've run `pytest python/ray/data/tests/preprocessors/test_imputer.py` locally and verified all tests pass. --------- Signed-off-by: Parth Vadera <[email protected]> Co-authored-by: Copilot <[email protected]>

Why are these changes needed?
Encoder preprocessors (
OrdinalEncoder,OneHotEncoder,MultiHotEncoder,LabelEncoder,Categorizer) currently fit throughcompute_unique_value_indices: amap_batchesthat emits per-block valuecounters, 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 scalabilitybottleneck, 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:
Unique(orTopKUniquewhenmax_categoriesis set) with the same
unique_values({col})alias the transform code reads.SimpleImputer("most_frequent")registersTopKUnique(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(andTopKUnique) fall back to collecting values in Python whenthe vectorized path can't handle a column's type: types without an Arrow
unique/value_countskernel, such as tensor columns, and list-typedcolumns when the optional
polarspackage isn't installed. Lists andarrays become tuples, so the encoders produce the same categories as
before.
HASHlist encoding still requirespolars, since a Pythonfallback 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_categoriesare 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_indicesand_get_most_frequent_valuesare removed; nothing uses them.Behavior notes for reviewers:
ds.aggregate(Unique(...))on a tensor column, or on a list column withoutpolarsinstalled, now works instead of raising. This comes from thefallback above and benefits any
Uniqueuser, not only the encoders.aggregates, with or without
polars(see the new tests below).max_categories, a null tied with a real value at the cut-off nolonger 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.
column is typed
nullrather thanlist, so its nulls count as a valueand 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
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).
callable stats); most_frequent never imputes null (including
None,NaN,pd.NAand float32NaN, 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 partialaggregates; encoders fit tensor columns (whole arrays, flattened arrays,
max_categories); whole-list encoding with and withoutpolars;Uniqueon tensor columns and on list columns withoutpolars;HASHmode still requires
polars; a null row in a list column adds nocategories.
AI assistance was used to draft this change (Claude Code); every line has been
reviewed by the submitter.
🤖 Generated with Claude Code